diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index 1b4b0e3..5c55520 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -57,9 +57,9 @@ issue. `.pre-commit-config.yaml` takes the slow path, which installs the pinned tools and collections. *Why:* a pull request is tested on its own pins, and an unchanged one starts in seconds. *Held:* control: the "Check the baked tooling against the pins" step. -- **Triggers:** both run on pull requests to `main`, on push to `main` until #166 removes that - trigger, and on manual dispatch; Build also runs on `v*` tags, where it checks the tag against - `galaxy.yml`. *Why:* the tag is what consumers install. *Held:* review. +- **Triggers:** both run on pull requests to `main` and on manual dispatch; Build also runs on + `v*` tags, where it checks the tag against `galaxy.yml`. *Why:* the tag is what consumers + install. *Held:* review. ## Molecule @@ -79,29 +79,30 @@ issue. belongs there only if no scenario reads it.** *Why:* a file a scenario reads but the selector ignores would let a breaking change through untested. *Held:* review. - **Every scenario runs on a manual dispatch and in the nightly run (04:43 UTC, after - Renovate's).** A push to `main` that touches the `push:` `paths:` list runs every scenario - too, until #166 removes that trigger. *Why:* a pull request runs only its selection, so - drift in the other roles shows up here. *Held:* review. -- **A new commit cancels the pull request's running Molecule run, and the run step first removes - the containers a cancelled run left.** The scenarios of one run overlap - (`scripts/run_molecule_scenarios.sh`, `MOLECULE_LANES` at a time), so no two scenarios may share a - platform name. Two runs never overlap only because the runner has a single slot, and the - scenarios' container names are fixed; raising the runner's capacity needs per-run container - names first (#166). *Why:* a cancelled run is killed before it can remove its instances, and - two overlapping scenarios or runs would collide on the same names. *Held:* review; that no two - scenarios share a platform name is held by the test the `test_sequence` rule below names. + Renovate's).** A push to `main` runs no Molecule. *Why:* a pull request runs only its + selection, so drift in the other roles shows up here. *Held:* review. +- **A new commit cancels the pull request's running Molecule run; every other run has a + concurrency group of its own.** Runs may overlap on the runner's Docker daemon: every container + is named and labelled by its run (`KAMINO_RUN_ID`). The job first removes labelled containers + older than its timeout, which a cancelled run left, and finally its own. The scenarios of one + run overlap (`scripts/run_molecule_scenarios.sh`, `MOLECULE_LANES` at a time), so no two + scenarios may share a platform name. *Why:* a cancelled run is killed before it can remove its + instances, and a younger container may belong to a run still going. *Held:* review; the names + and labels are held by the test the `test_sequence` rule below names. - **Molecule tests the pull request's pins, as Lint and Build do.** It runs molecule in the pinned `ci` image and, when a pin file differs from `/opt/ci-pins.sha256`, installs the pull request's tools and the collections of `requirements.yml` and `extensions/molecule/requirements.yml` first. *Why:* a pull request that raises the ansible-core floor must run its scenarios on the new core before it automerges. *Held:* control: the pin comparison in `molecule.yml`. - **Every scenario sets `scenario.test_sequence` to molecule's default minus both `destroy` - steps, and names its platforms literally in its `molecule.yml`;** copy it into a new scenario. - *Why:* the workflow clears stale containers first and removes each scenario's containers by - those names as soon as it ends, which skips the driver's destroy wait, and the molecule state - lives in each scenario's own `ANSIBLE_HOME` in the job tree, so a killed run leaves none - behind. *Held:* control: `tests/scripts/test_run_molecule_scenarios.py` fails a `destroy` in a - sequence, and a platform name that is not unique or not matched by the stale-container filter. + steps, names each platform `${KAMINO_RUN_ID:-local}-` and labels it + `net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}"` in its `molecule.yml`;** copy it into + a new scenario. *Why:* the run script removes each scenario's containers by those names as soon + as it ends, which skips the driver's destroy wait, the workflow finds a run's containers by the + label, and the molecule state lives in each scenario's own `ANSIBLE_HOME` in the job tree, so a + killed run leaves none behind. *Held:* control: `tests/scripts/test_run_molecule_scenarios.py` + fails a `destroy` in a sequence, a platform name that is not unique or not per run, a missing + label, and a workflow that does not filter by it. - **Scenarios live in `roles/*/molecule/*/` and `extensions/molecule/*/`.** A role scenario that must pass on Ubuntu 24.04 and 26.04 takes `image: ${MOLECULE_IMAGE}` or `${MOLECULE_IMAGE_2604}` per platform; the image-smoke scenarios are described in diff --git a/.gitea/workflows/build.yml b/.gitea/workflows/build.yml index 3cb0a57..a93643c 100644 --- a/.gitea/workflows/build.yml +++ b/.gitea/workflows/build.yml @@ -9,8 +9,6 @@ on: # yamllint disable-line rule:truthy branches: - main push: - branches: - - main tags: - 'v*' workflow_dispatch: {} @@ -18,11 +16,10 @@ on: # yamllint disable-line rule:truthy permissions: contents: read -# A newer push to the same pull request cancels the running run; a push to main or a tag -# never cancels another run. A tag run has its own group, so it never shares one with the -# main run of the same commit. +# A newer push to the same pull request cancels the running run. A tag's ref differs from every +# branch's, so a tag run has a group of its own and is never cancelled. concurrency: - group: build-${{ github.event_name == 'pull_request' && github.ref || (github.ref_type == 'tag' && github.ref || github.sha) }} + group: build-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index 0380455..7d51990 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -12,19 +12,15 @@ on: # yamllint disable-line rule:truthy pull_request: branches: - main - push: - branches: - - main workflow_dispatch: {} permissions: contents: read -# A newer push to the same pull request makes the running run obsolete. A push to main is -# never cancelled: each merge commit keeps its own result, so its group is the commit SHA. -# (This workflow has no tag trigger, so no tag branch in the group.) +# A newer push to the same pull request makes the running run obsolete; a manual dispatch never +# cancels another run. concurrency: - group: lint-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + group: lint-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: diff --git a/.gitea/workflows/molecule.yml b/.gitea/workflows/molecule.yml index a403263..213a8a1 100644 --- a/.gitea/workflows/molecule.yml +++ b/.gitea/workflows/molecule.yml @@ -20,20 +20,8 @@ on: # yamllint disable-line rule:truthy pull_request: branches: - main - push: - branches: - - main - paths: - - 'roles/**' - - 'extensions/**' - - 'plugins/**' - - 'meta/**' - - 'galaxy.yml' - - 'requirements.yml' - - '.gitea/workflows/molecule.yml' # Every scenario, nightly: a pull request runs only the scenarios of the roles it changes, so - # drift in the others (a package mirror) would otherwise wait for - # the next push to main. After Renovate's 03:17 run, which can take 30 minutes of the one slot. + # drift in the others (a package mirror) would otherwise go unseen. After Renovate's 03:17 run. schedule: - cron: "43 4 * * *" workflow_dispatch: {} @@ -41,21 +29,17 @@ on: # yamllint disable-line rule:truthy permissions: contents: read -# A pull request run is cancelled when a newer commit is pushed to the same pull request (the -# same rule as lint.yml and build.yml); a run on main is never cancelled, so its group is the -# commit SHA. The scenarios of one run overlap (scripts/run_molecule_scenarios.sh), which is safe -# because no two share a container name; but the names are fixed on the runner's shared Docker -# daemon, so two runs must not overlap. The group no longer guarantees that (it is per pull -# request now): the runner's single slot does. Raise the runner's capacity and this needs -# per-run container names first (#166), or a lock or a shared group again. +# A newer push to a pull request cancels its older run; every other run has a group of its own, so +# none is cancelled. Runs may overlap on the runner's Docker daemon: every container is named and +# labelled by its run (KAMINO_RUN_ID), and no two scenarios share a platform name. concurrency: - group: molecule-${{ github.event_name == 'pull_request' && github.ref || github.sha }} + group: molecule-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: molecule: # Same-repo branches only (bot branches included: a Renovate pin pull request is what tests a new - # image); a push to main or a manual dispatch always runs. No paths filter on pull requests, so + # image); the nightly run and a manual dispatch always run. No paths filter on pull requests, so # that Molecule can be a required check: a required check that a pull request never starts would # block it. A fork pull request is skipped by the guard below. if: >- @@ -76,7 +60,9 @@ jobs: # `image: ${MOLECULE_IMAGE_2604}` in extensions/molecule/image-smoke-2604. MOLECULE_IMAGE_2604: >- git.rkdr.net/mortis/molecule-ubuntu2604:0.1.6@sha256:d7c216b33d18fa8f1ecbfee8795eb4adc867fe5ad8e7a73b7c67effe301cf771 - # The container molecule runs in, named and labelled by the run so the cleanup step finds it. + # Names and labels this run's containers: the scenarios' as `${KAMINO_RUN_ID:-local}-` + # with the label net.rkdr.mortis.molecule-run, and the one molecule runs in. + KAMINO_RUN_ID: ${{ github.run_id }}-${{ github.run_attempt }} RUN_CONTAINER: kamino-molecule-${{ github.run_id }}-${{ github.run_attempt }} steps: - name: Check the Docker daemon @@ -101,10 +87,23 @@ jobs: git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; } echo "Checked out $(git rev-parse HEAD)" + # A cancelled run is killed before it can remove its containers. Any labelled container older + # than the job timeout is such a leftover; a younger one may belong to a run still going. + - name: Remove the containers earlier runs left + run: | + # Assigned first so that a failing `docker ps` fails the step instead of looking empty. + ids="$(docker ps -aq --filter 'label=net.rkdr.mortis.molecule-run')" + cutoff="$(date -d '30 minutes ago' +%s)" + for id in $ids; do + # a container removed since the listing is skipped + created="$(docker inspect --format '{{.Created}}' "$id")" || continue + if [ "$(date -d "$created" +%s)" -lt "$cutoff" ]; then docker rm -f "$id"; fi + done + # A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py - # explains the rules); a push to main and a manual dispatch run all of them, a few at a time. + # explains the rules); the nightly run and a manual dispatch run all of them, a few at a time. # scripts/run_molecule_scenarios.sh runs them and removes each scenario's containers as soon as - # it ends; a cancelled run is killed before it can, so the step first removes what one left. + # it ends. - name: Run the scenarios working-directory: ac/ansible_collections/mortis/kamino env: @@ -112,13 +111,6 @@ jobs: # The workflow only runs for pull requests to main; lint.yml uses the same constant. BASE_REF: origin/main run: | - # The platform names of every scenario, anchored: -instance and image-smoke[-2604]. - # Assigned first so that a failing `docker ps` fails the step instead of looking empty. - stale="$(docker ps -aq --filter 'name=^/[a-z0-9-]+-instance$' --filter 'name=^/image-smoke(-2604)?$')" - if [ -n "$stale" ]; then - # shellcheck disable=SC2086 # container ids, one word each - docker rm -f $stale - fi # The selector comes from the base branch, so a pull request cannot edit the rules it is # judged by (lint.yml does the same for check_bot_pr_diff.py); the first pull request that # adds it has no base copy yet and uses its own. @@ -144,18 +136,21 @@ jobs: printf 'root:x:0:0:root:/root:/bin/bash\n%s:x:%s:%s::%s:/bin/bash\n' \ "$(id -un)" "$(id -u)" "$(id -g)" "$ac_root/home" > "$ac_root/passwd" docker run --rm -i --init --name "$RUN_CONTAINER" \ - --label "net.rkdr.mortis.molecule-run=$RUN_CONTAINER" \ + --label "net.rkdr.mortis.molecule-run=$KAMINO_RUN_ID" \ --user "$(id -u):$(id -g)" --group-add "$sock_gid" \ -v /var/run/docker.sock:/var/run/docker.sock -v "$docker_cli:/usr/local/bin/docker:ro" \ -v "$ac_root:$ac_root" -v "$ac_root/passwd:/etc/passwd:ro" -w "$PWD" \ -e "AC_ROOT=$ac_root" -e "HOME=$ac_root/home" -e "USER=$(id -un)" \ - -e MOLECULE_IMAGE -e MOLECULE_IMAGE_2604 \ + -e MOLECULE_IMAGE -e MOLECULE_IMAGE_2604 -e KAMINO_RUN_ID \ "$CI_IMAGE" scripts/run_molecule_in_ci_image.sh <<< "$selected" - # A cancelled run can leave the container running when the docker client is killed. - - name: Remove the molecule container + # A cancelled run can leave its containers running when the docker client is killed. + - name: Remove this run's containers if: always() run: | - if docker container inspect "$RUN_CONTAINER" >/dev/null 2>&1; then - docker rm -f "$RUN_CONTAINER" + # Assigned first so that a failing `docker ps` fails the step instead of looking empty. + ids="$(docker ps -aq --filter "label=net.rkdr.mortis.molecule-run=$KAMINO_RUN_ID")" + if [ -n "$ids" ]; then + # shellcheck disable=SC2086 # container ids, one word each + docker rm -f $ids fi diff --git a/extensions/molecule/image-smoke-2604/molecule.yml b/extensions/molecule/image-smoke-2604/molecule.yml index e48277f..cabbc9b 100644 --- a/extensions/molecule/image-smoke-2604/molecule.yml +++ b/extensions/molecule/image-smoke-2604/molecule.yml @@ -6,7 +6,9 @@ driver: name: docker platforms: - - name: image-smoke-2604 + - name: ${KAMINO_RUN_ID:-local}-image-smoke-2604 + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE_2604} pre_build_image: true pull: true @@ -26,9 +28,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/extensions/molecule/image-smoke/molecule.yml b/extensions/molecule/image-smoke/molecule.yml index c7cc31a..d71414c 100644 --- a/extensions/molecule/image-smoke/molecule.yml +++ b/extensions/molecule/image-smoke/molecule.yml @@ -6,7 +6,9 @@ driver: name: docker platforms: - - name: image-smoke + - name: ${KAMINO_RUN_ID:-local}-image-smoke + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -26,9 +28,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/_binary_update/molecule/check_mode/molecule.yml b/roles/_binary_update/molecule/check_mode/molecule.yml index 86bda56..e745df8 100644 --- a/roles/_binary_update/molecule/check_mode/molecule.yml +++ b/roles/_binary_update/molecule/check_mode/molecule.yml @@ -6,7 +6,9 @@ driver: name: docker platforms: - - name: binary-update-check-instance + - name: ${KAMINO_RUN_ID:-local}-binary-update-check-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -26,9 +28,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/_binary_update/molecule/default/molecule.yml b/roles/_binary_update/molecule/default/molecule.yml index dc90ed8..d8cc228 100644 --- a/roles/_binary_update/molecule/default/molecule.yml +++ b/roles/_binary_update/molecule/default/molecule.yml @@ -6,7 +6,9 @@ driver: name: docker platforms: - - name: binary-update-instance + - name: ${KAMINO_RUN_ID:-local}-binary-update-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -26,9 +28,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/cloudflared/molecule/default/molecule.yml b/roles/cloudflared/molecule/default/molecule.yml index f49d14a..8e17d0f 100644 --- a/roles/cloudflared/molecule/default/molecule.yml +++ b/roles/cloudflared/molecule/default/molecule.yml @@ -11,7 +11,9 @@ driver: name: docker platforms: - - name: cloudflared-instance + - name: ${KAMINO_RUN_ID:-local}-cloudflared-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -71,9 +73,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/docker/molecule/default/molecule.yml b/roles/docker/molecule/default/molecule.yml index 584106e..1c1488c 100644 --- a/roles/docker/molecule/default/molecule.yml +++ b/roles/docker/molecule/default/molecule.yml @@ -7,7 +7,9 @@ driver: name: docker platforms: - - name: docker-instance + - name: ${KAMINO_RUN_ID:-local}-docker-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -27,9 +29,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/fail2ban/molecule/default/molecule.yml b/roles/fail2ban/molecule/default/molecule.yml index c51cdfc..d36e0e1 100644 --- a/roles/fail2ban/molecule/default/molecule.yml +++ b/roles/fail2ban/molecule/default/molecule.yml @@ -5,7 +5,9 @@ driver: name: docker platforms: - - name: fail2ban-instance + - name: ${KAMINO_RUN_ID:-local}-fail2ban-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -25,9 +27,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/gitea/molecule/default/molecule.yml b/roles/gitea/molecule/default/molecule.yml index 9cdf06c..d6863c8 100644 --- a/roles/gitea/molecule/default/molecule.yml +++ b/roles/gitea/molecule/default/molecule.yml @@ -11,7 +11,9 @@ driver: name: docker platforms: - - name: gitea-instance + - name: ${KAMINO_RUN_ID:-local}-gitea-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -36,9 +38,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/gitea_runner/molecule/default/molecule.yml b/roles/gitea_runner/molecule/default/molecule.yml index 65720ce..f4b915b 100644 --- a/roles/gitea_runner/molecule/default/molecule.yml +++ b/roles/gitea_runner/molecule/default/molecule.yml @@ -8,7 +8,9 @@ driver: name: docker platforms: - - name: runner-instance + - name: ${KAMINO_RUN_ID:-local}-runner-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -46,9 +48,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/network_interfaces/molecule/default/molecule.yml b/roles/network_interfaces/molecule/default/molecule.yml index b1fafb9..e7c156a 100644 --- a/roles/network_interfaces/molecule/default/molecule.yml +++ b/roles/network_interfaces/molecule/default/molecule.yml @@ -5,7 +5,9 @@ driver: name: docker platforms: - - name: network-interfaces-instance + - name: ${KAMINO_RUN_ID:-local}-network-interfaces-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -25,9 +27,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/sshd/molecule/default/molecule.yml b/roles/sshd/molecule/default/molecule.yml index b4a5bd9..f56e5b0 100644 --- a/roles/sshd/molecule/default/molecule.yml +++ b/roles/sshd/molecule/default/molecule.yml @@ -6,7 +6,9 @@ driver: name: docker platforms: - - name: sshd-instance + - name: ${KAMINO_RUN_ID:-local}-sshd-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -26,9 +28,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/system_baseline/molecule/default/molecule.yml b/roles/system_baseline/molecule/default/molecule.yml index eab31f5..bce25f6 100644 --- a/roles/system_baseline/molecule/default/molecule.yml +++ b/roles/system_baseline/molecule/default/molecule.yml @@ -8,7 +8,9 @@ driver: name: docker platforms: - - name: system-baseline-instance + - name: ${KAMINO_RUN_ID:-local}-system-baseline-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -32,9 +34,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/systemd_hardening/molecule/default/molecule.yml b/roles/systemd_hardening/molecule/default/molecule.yml index eee4b49..525365e 100644 --- a/roles/systemd_hardening/molecule/default/molecule.yml +++ b/roles/systemd_hardening/molecule/default/molecule.yml @@ -5,7 +5,9 @@ driver: name: docker platforms: - - name: systemd-hardening-instance + - name: ${KAMINO_RUN_ID:-local}-systemd-hardening-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -25,9 +27,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/traefik/molecule/default/molecule.yml b/roles/traefik/molecule/default/molecule.yml index 1df2c55..85012ea 100644 --- a/roles/traefik/molecule/default/molecule.yml +++ b/roles/traefik/molecule/default/molecule.yml @@ -6,7 +6,9 @@ driver: name: docker platforms: - - name: traefik-instance + - name: ${KAMINO_RUN_ID:-local}-traefik-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -46,9 +48,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/ufw/molecule/default/molecule.yml b/roles/ufw/molecule/default/molecule.yml index 7bd9940..cd45b2c 100644 --- a/roles/ufw/molecule/default/molecule.yml +++ b/roles/ufw/molecule/default/molecule.yml @@ -5,7 +5,9 @@ driver: name: docker platforms: - - name: ufw-instance + - name: ${KAMINO_RUN_ID:-local}-ufw-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -25,9 +27,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/roles/user_management/molecule/default/molecule.yml b/roles/user_management/molecule/default/molecule.yml index 81b223c..bec3981 100644 --- a/roles/user_management/molecule/default/molecule.yml +++ b/roles/user_management/molecule/default/molecule.yml @@ -5,7 +5,9 @@ driver: name: docker platforms: - - name: user-management-instance + - name: ${KAMINO_RUN_ID:-local}-user-management-instance + labels: + net.rkdr.mortis.molecule-run: "${KAMINO_RUN_ID:-local}" image: ${MOLECULE_IMAGE} pre_build_image: true pull: true @@ -33,9 +35,9 @@ provisioner: verifier: name: ansible scenario: - # molecule's default sequence minus both destroys: the workflow removes the container before the - # run and as soon as this scenario ends; molecule's destroy only adds the driver's poll wait. - # After a local run, run `molecule destroy` yourself. + # molecule's default sequence minus both destroys: the workflow removes the container as soon as + # this scenario ends, and a later run removes one a killed run left; molecule's destroy only adds + # the driver's poll wait. After a local run, run `molecule destroy` yourself. test_sequence: - dependency - cleanup diff --git a/scripts/run_molecule_scenarios.sh b/scripts/run_molecule_scenarios.sh index 34400e7..3b181c7 100755 --- a/scripts/run_molecule_scenarios.sh +++ b/scripts/run_molecule_scenarios.sh @@ -24,19 +24,23 @@ label_of() { esac } -# Removes the scenario's containers by the literal platform names in its molecule.yml, in place of -# molecule's destroy, which the scenarios leave out: its driver waits about 5.6 s per scenario for -# the deletion (about 84 s over 15), and the whole destroy phase measured about 103 s a full run. -# The ci image has no docker CLI: python3 is the one molecule runs on, with PyYAML and the Docker -# SDK of molecule's Docker driver. +# Removes the scenario's containers by the platform names in its molecule.yml, expanded as molecule +# expands them (they carry ${KAMINO_RUN_ID}), in place of molecule's destroy, which the scenarios +# leave out: its driver waits about 5.6 s per scenario for the deletion (about 84 s over 15), and +# the whole destroy phase measured about 103 s a full run. The ci image has no docker CLI: python3 +# is the one molecule runs on, with molecule, PyYAML and the Docker SDK of molecule's Docker driver. remove_instances() { python3 -I - "$1/molecule.yml" <<'EOF' +import os import sys import docker import yaml +from molecule.interpolation import Interpolator, TemplateWithDefaults -names = [p["name"] for p in yaml.safe_load(open(sys.argv[1]))["platforms"]] +with open(sys.argv[1]) as f: + text = Interpolator(TemplateWithDefaults, os.environ).interpolate(f.read()) +names = [p["name"] for p in yaml.safe_load(text)["platforms"]] if not names: sys.exit("no platform names in " + sys.argv[1]) containers = docker.from_env().containers diff --git a/scripts/select_molecule_scenarios.py b/scripts/select_molecule_scenarios.py index 66bb14b..7147069 100644 --- a/scripts/select_molecule_scenarios.py +++ b/scripts/select_molecule_scenarios.py @@ -33,7 +33,7 @@ everything. Every other case runs everything: a push, a manual dispatch, a scheduled run, no , a git failure. Narrowing is an optimisation, so any doubt resolves to the full set. The scenarios the -selection skips are not skipped on `main`: the push run after the merge runs them all. +selection skips still run on `main`: the nightly run and a manual dispatch run them all. A changed role that exists but has no scenario is an error, not an empty selection: a new role without a molecule scenario, or a deleted or renamed scenario, must not pass Molecule with @@ -42,7 +42,7 @@ nothing tested. A role whose directory is gone (the role was deleted) selects no The workflow runs this script from the base branch's copy, not the pull request's, so a pull request cannot edit the rules it is judged by (the same reason lint.yml runs check_bot_pr_diff.py from origin/main). No scenario runs the pull request's copy, so this file -is on the IGNORED list: its unit tests test it, and the push run after the merge runs it. +is on the IGNORED list: its unit tests test it, and the nightly run and a manual dispatch run it. Exit codes: 0 ok (an empty selection from an all-ignored diff is ok), 1 no scenario exists at all, or a changed role has none, 2 bad usage. Notices go to stderr as `::notice::` lines, with diff --git a/tests/scripts/test_run_molecule_scenarios.py b/tests/scripts/test_run_molecule_scenarios.py index 6e0b7ba..22f208d 100644 --- a/tests/scripts/test_run_molecule_scenarios.py +++ b/tests/scripts/test_run_molecule_scenarios.py @@ -5,6 +5,7 @@ Run with: python3 -m unittest discover -s tests/scripts """ +import importlib.util import os import pathlib import re @@ -21,6 +22,11 @@ import yaml REPO = pathlib.Path(__file__).resolve().parents[2] SCRIPT = REPO / "scripts" / "run_molecule_scenarios.sh" WORKFLOW = REPO / ".gitea" / "workflows" / "molecule.yml" +RUN_ID = "${KAMINO_RUN_ID:-local}" +RUN_LABEL = "net.rkdr.mortis.molecule-run" +# The script expands platform names with molecule's own interpolator, as molecule does. +HAS_MOLECULE = importlib.util.find_spec("molecule") is not None +NEEDS_MOLECULE = "the run script imports molecule to expand platform names" # Records what each run saw, then behaves as STUB_ asks: fail, sleep, hang (and # record its pids), detach (as an ansible worker does, into its own process group, whose orphaned @@ -94,8 +100,11 @@ def stub_python(where): ).stdout.strip() site = pathlib.Path(site) (site / "docker.py").write_text(DOCKER_SDK_STUB) - # PyYAML from the environment running the tests - (site / "outer.pth").write_text(str(pathlib.Path(yaml.__file__).parents[1]) + "\n") + # PyYAML, and molecule when it is there, from the environment running the tests + outer = {pathlib.Path(yaml.__file__).parents[1]} + if HAS_MOLECULE: + outer.add(pathlib.Path(importlib.util.find_spec("molecule").origin).parents[1]) + (site / "outer.pth").write_text("".join(f"{p}\n" for p in outer)) return where / "bin" @@ -107,6 +116,11 @@ PLATFORMS = { } +def container_names(run_id): + """Every fixture platform's container name in the run run_id.""" + return [f"{run_id}-{n}" for names in PLATFORMS.values() for n in names] + + @unittest.skipUnless(shutil.which("bash"), "bash is required") class RunMoleculeScenariosTest(unittest.TestCase): @classmethod @@ -126,7 +140,9 @@ class RunMoleculeScenariosTest(unittest.TestCase): for scenario, names in PLATFORMS.items(): d = self.root / scenario d.mkdir(parents=True) - platforms = [{"name": n, "image": "${MOLECULE_IMAGE}"} for n in names] + platforms = [ + {"name": f"{RUN_ID}-{n}", "image": "${MOLECULE_IMAGE}"} for n in names + ] (d / "molecule.yml").write_text(yaml.safe_dump({"platforms": platforms})) bin_dir = self.tmp / "bin" bin_dir.mkdir() @@ -163,6 +179,7 @@ class RunMoleculeScenariosTest(unittest.TestCase): times.setdefault(label, {})[what] = float(stamp) return {k: (v["start"], v.get("end")) for k, v in times.items()} + @unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE) def test_groups_follow_the_selection_order_with_times(self): order = list(PLATFORMS) proc = self.run_script(order, STUB_alpha_default="sleep") @@ -185,6 +202,7 @@ class RunMoleculeScenariosTest(unittest.TestCase): self.assertIn("Scenarios run: 4", proc.stdout) self.assertIn(" image-smoke: ", proc.stdout) + @unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE) def test_runs_in_lanes_and_isolates_each_scenario(self): order = list(PLATFORMS) stubs = { @@ -211,13 +229,14 @@ class RunMoleculeScenariosTest(unittest.TestCase): smoke = next(s for s in starts if s.startswith("image-smoke ")) self.assertIn(f"cwd={self.root} args=test -s image-smoke", smoke) + @unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE) def test_a_failure_is_reported_and_its_containers_still_go(self): proc = self.run_script(list(PLATFORMS), STUB_beta_default="fail") self.assertEqual(proc.returncode, 1) self.assertIn("::error::Failed: beta/default\n", proc.stdout) self.assertIn("Scenarios run: 4", proc.stdout) docker = self.docker_log.read_text().splitlines() - for name in (n for names in PLATFORMS.values() for n in names): + for name in container_names("local"): self.assertIn(f"list {name} all=True", docker) self.assertIn(f"remove {name} force=True", docker) # a filter match by another name is left alone @@ -225,12 +244,25 @@ class RunMoleculeScenariosTest(unittest.TestCase): [line for line in docker if line.endswith("-other force=True")] ) + @unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE) + def test_the_containers_removed_are_the_run_s_own(self): + proc = self.run_script(list(PLATFORMS), KAMINO_RUN_ID="r7") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + removed = [ + line.split()[1] + for line in self.docker_log.read_text().splitlines() + if line.startswith("remove ") + ] + self.assertEqual(sorted(removed), sorted(container_names("r7"))) + + @unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE) def test_molecule_gets_no_stdin(self): proc = self.run_script(list(PLATFORMS), STUB_alpha_default="stdin") self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("stdin of alpha/default: []", proc.stdout) self.assertIn("Scenarios run: 4", proc.stdout) + @unittest.skipUnless(HAS_MOLECULE, NEEDS_MOLECULE) def test_a_failed_removal_fails_the_scenario(self): proc = self.run_script(["roles/alpha/molecule/default"], STUB_RM_FAIL="1") self.assertEqual(proc.returncode, 1) @@ -326,32 +358,32 @@ def alive(pid): return stat.rsplit(")", 1)[1].split()[0] != "Z" -def stale_filters(): - """The name filters of the workflow's stale-container cleanup, as docker matches /.""" +def label_filters(): + """The label filters of the workflow's docker commands, as `--filter label=[=]`.""" workflow = yaml.safe_load(WORKFLOW.read_text()) steps = [s for job in workflow["jobs"].values() for s in job.get("steps", [])] - run = next(s["run"] for s in steps if s.get("name") == "Run the scenarios") - stale = next(line for line in run.splitlines() if line.strip().startswith("stale=")) - return re.findall(r"--filter 'name=([^']+)'", stale) + runs = "\n".join(s.get("run", "") for s in steps) + return re.findall(r"--filter ['\"]?label=([^'\"\s]+)", runs) -class ScenarioPlatformNamesTest(unittest.TestCase): - """The run script removes containers by literal platform name, and scenarios run side by side.""" +class ScenarioPlatformsTest(unittest.TestCase): + """Scenarios run side by side and runs overlap, so each container is named and labelled by its run.""" - def test_platform_names_are_literal_unique_and_cleared_before_a_run(self): + def test_platforms_are_named_and_labelled_by_the_run(self): files = sorted(REPO.glob("roles/*/molecule/*/molecule.yml")) files += sorted(REPO.glob("extensions/molecule/*/molecule.yml")) self.assertTrue(files) seen = {} - stale = stale_filters() - self.assertTrue(stale) for path in files: + where = path.relative_to(REPO) data = yaml.safe_load(path.read_text()) for platform in data["platforms"]: name = platform["name"] - where = path.relative_to(REPO) - self.assertTrue( - any(re.search(f, f"/{name}") for f in stale), f"{where}: {name}" + self.assertTrue(name.startswith(f"{RUN_ID}-"), f"{where}: {name}") + self.assertEqual( + platform.get("labels", {}).get(RUN_LABEL), + RUN_ID, + f"{where}: {name}", ) self.assertNotIn( name, seen, f"{where} and {seen.get(name)} share {name}" @@ -359,6 +391,12 @@ class ScenarioPlatformNamesTest(unittest.TestCase): seen[name] = where self.assertNotIn("destroy", data["scenario"]["test_sequence"], path) + def test_the_workflow_finds_the_containers_by_the_run_label(self): + filters = label_filters() + # the sweep of earlier runs filters by the key, the cleanup of this run by key and value + self.assertIn(RUN_LABEL, filters) + self.assertIn(f"{RUN_LABEL}=$KAMINO_RUN_ID", filters) + if __name__ == "__main__": unittest.main()