diff --git a/.gitea/workflows/AGENTS.md b/.gitea/workflows/AGENTS.md index ff66a14..882da29 100644 --- a/.gitea/workflows/AGENTS.md +++ b/.gitea/workflows/AGENTS.md @@ -72,11 +72,23 @@ issue. ## Molecule - **Molecule runs on every same-repository pull request, Renovate's included, with no path - filter.** A fork pull request is skipped by the job's `if:`, which is a convenience, not a + filter.** A fork pull request is skipped by the jobs' shared `if:` guard, which is a convenience, not a boundary: a fork controls its own workflow file. Gitea's approval gate keeps a fork's runs from starting, and the fork rule in [reviewing.md](../../docs/contributing/reviewing.md) keeps it shut. *Why:* a check that always reports can be required, and a new image is tested by its own pin pull request. *Held:* review. +- **Molecule has three jobs: `select`, `scenarios` and `result`.** `select` runs the selector in + a job container on `kamino-docker`, in the `molecule-controller` pin (never the `ci` pin, whose + bumps would then select every scenario), and outputs the selected directories. `scenarios` + runs them on `kamino-molecule` and is skipped when the list is empty. `result` (check + `Molecule / Result (pull_request)`) is the required check: it runs `if: always()` and fails + unless `select` passed and `scenarios` passed or was skipped for an empty list. The + controller pin is written in all three jobs, because `container.image` cannot read `env`. + *Why:* a pull request that selects nothing takes no Molecule runner slot, and a skipped job + counts as passing in Gitea, so only a job that always runs can be required. *Held:* control: + `WorkflowJobsTest` in `tests/scripts/test_run_molecule_scenarios.py` for the jobs, runners, + guard and result logic, and `test_every_controller_pin_is_the_same` in + `tests/scripts/test_select_molecule_scenarios.py` for the pin copies. - **What a pull request runs is chosen by `scripts/select_molecule_scenarios.py`:** the scenarios of the roles it changes and of the roles that use them (any file naming `mortis.kamino.`, transitively), none for a diff of only IGNORED paths, a failure for a diff --git a/.gitea/workflows/molecule.yml b/.gitea/workflows/molecule.yml index 1d93373..882726d 100644 --- a/.gitea/workflows/molecule.yml +++ b/.gitea/workflows/molecule.yml @@ -4,8 +4,13 @@ name: Molecule # extensions/molecule/*/ and roles/*/molecule/*/. extensions/molecule/image-smoke and # image-smoke-2604 test the test images themselves, so they run even before any role exists. # -# It runs on the `kamino-molecule` label, a host executor that uses the runner's own -# Docker daemon; no job container is given the Docker socket. That makes the job +# Three jobs, so that a pull request that selects no scenario takes no Molecule runner slot: +# `select` chooses the scenarios in a job container on `kamino-docker`; `scenarios` runs them on +# `kamino-molecule`, and is skipped when none is selected; `result` is the required check and +# passes only when `select` passed and `scenarios` passed or was skipped for an empty selection. +# +# The scenarios job runs on the `kamino-molecule` label, a host executor that uses the runner's +# own Docker daemon; no job container is given the Docker socket. That makes the job # root-equivalent on the runner, which is disposable and holds no secret from outside # this repository. The `if:` guard is a convenience filter, not a boundary: a fork controls its # own workflow file. The boundaries are write access, which only trusted people have, and Gitea's @@ -16,7 +21,8 @@ name: Molecule # at the same path, so the paths molecule hands the daemon resolve. Like Lint and Build, it installs # the pull request's pins when they differ from the image's. The images are pinned by tag and # digest: bump them here when image.yml publishes a new molecule-controller, molecule-ubuntu2404 or -# molecule-ubuntu2604 version. +# molecule-ubuntu2604 version. The molecule-controller pin is written three times, because +# `container.image` cannot read `env`; a script test holds the copies equal. on: # yamllint disable-line rule:truthy pull_request: branches: @@ -44,15 +50,83 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - molecule: + select: # Same-repo branches only (bot branches included: a Renovate pin pull request is what tests a new # 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. + # block it. A fork pull request is skipped by the guard below, which all three jobs share. if: >- github.repository == 'mortis/kamino' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) + runs-on: kamino-docker + timeout-minutes: 10 + # The molecule-controller pin, as CONTROLLER_IMAGE below: a ci pin here would make every ci + # bump select every scenario (ADR 0003). + container: + image: git.rkdr.net/mortis/molecule-controller:0.1.1@sha256:94af071ecae858016f9a61afa6e45f8344f8fef7d22d1fe899e05f5f48f756e8 + outputs: + scenarios: ${{ steps.select.outputs.scenarios }} + steps: + # The selector's diff needs origin/main and the full history, so a clone, not a fetch of HEAD. + - name: Checkout the commit under test + env: + GIT_CONFIG_COUNT: "1" + GIT_CONFIG_KEY_0: http.extraheader + GIT_CONFIG_VALUE_0: "AUTHORIZATION: bearer ${{ secrets.GITHUB_TOKEN }}" + SHA: ${{ github.event.pull_request.head.sha || github.sha }} + REF: ${{ github.ref }} + REPO_URL: ${{ github.server_url }}/${{ github.repository }} + run: | + rm -rf ac + mkdir -p ac/ansible_collections/mortis + git clone "$REPO_URL" ac/ansible_collections/mortis/kamino + cd ac/ansible_collections/mortis/kamino + # A clone has no refs/pull/*: fetch the run's ref when the sha is not on a branch. + git checkout "$SHA" || { git fetch origin "$REF" && git checkout "$SHA"; } + echo "Checked out $(git rev-parse HEAD)" + + # A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py + # explains the rules); the nightly run and a manual dispatch run all of them, because the + # selector narrows only when EVENT_NAME is pull_request. + - name: Select the scenarios + id: select + working-directory: ac/ansible_collections/mortis/kamino + env: + EVENT_NAME: ${{ github.event_name }} + # The workflow only runs for pull requests to main; lint.yml uses the same constant. + BASE_REF: origin/main + run: | + # 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. + sel=scripts/select_molecule_scenarios.py + if git cat-file -e "$BASE_REF:$sel" 2>/dev/null; then + sel_dir="$(mktemp -d)" + trap 'rm -rf "$sel_dir"' EXIT + git show "$BASE_REF:$sel" > "$sel_dir/select.py" + sel="$sel_dir/select.py" + else + echo "::notice::no base copy of $sel; running this checkout's copy" + fi + selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1 + # One directory per line. A random delimiter, so no line of the list can end the value; + # an empty selection writes no line, so the output is the empty string. + delim="scenarios-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')" + { + echo "scenarios<<$delim" + if [ -n "$selected" ]; then printf '%s\n' "$selected"; fi + echo "$delim" + } >> "$GITHUB_OUTPUT" + + scenarios: + needs: select + # Skipped, not failed, when select fails or selects nothing; result tells the two apart. + if: >- + needs.select.outputs.scenarios != '' && + github.repository == 'mortis/kamino' && + (github.event_name != 'pull_request' || + github.event.pull_request.head.repo.full_name == github.repository) runs-on: [kamino-molecule] # A full run under load takes about 45 minutes (PR #405: 44m53s), so 45 left no margin. Also the # age past which the sweep step removes a run's containers; a script test holds the two equal. @@ -61,7 +135,7 @@ jobs: # The tools and collections molecule runs with, apart from Lint's (ADR 0003), so a tool # bump only Lint uses selects no scenario. CONTROLLER_IMAGE: >- - git.rkdr.net/mortis/molecule-controller:0.1.0@sha256:d4ab16d58851eead751c8f0bada8edd76c9e5dcd5c2acaa1ac93c5f6035b29e2 + git.rkdr.net/mortis/molecule-controller:0.1.1@sha256:94af071ecae858016f9a61afa6e45f8344f8fef7d22d1fe899e05f5f48f756e8 # Used by the scenarios as `image: ${MOLECULE_IMAGE}`; set it the same way to run # one locally. MOLECULE_IMAGE: >- @@ -121,33 +195,15 @@ jobs: for id in $old; do left="$left$(docker ps -aq --filter "id=$id")"; done if [ -n "$left" ]; then echo "::error::could not remove ${left//$'\n'/ }"; exit 1; fi - # A pull request runs only the scenarios of the roles it changes (scripts/select_molecule_scenarios.py - # 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. + # scripts/run_molecule_scenarios.sh runs the selected scenarios, a few at a time, and removes + # each scenario's containers as soon as it ends. - name: Run the scenarios working-directory: ac/ansible_collections/mortis/kamino env: - EVENT_NAME: ${{ github.event_name }} - # The workflow only runs for pull requests to main; lint.yml uses the same constant. - BASE_REF: origin/main + SELECTED: ${{ needs.select.outputs.scenarios }} # Empty outside a dispatch, which the run script reads as its default. MOLECULE_LANES: ${{ inputs.lanes }} run: | - # 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. - sel=scripts/select_molecule_scenarios.py - if git cat-file -e "$BASE_REF:$sel" 2>/dev/null; then - sel_dir="$(mktemp -d)" - trap 'rm -rf "$sel_dir"' EXIT - git show "$BASE_REF:$sel" > "$sel_dir/select.py" - sel="$sel_dir/select.py" - else - echo "::notice::no base copy of $sel; running this checkout's copy" - fi - selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1 - # As the runner user, with the socket's group, so nothing in the job tree is left root-owned. # HOME (ansible's temp and caches) is in the job tree; a mounted passwd entry points the user # at it, because ansible's temp path is `~/.ansible/tmp`. The driver's connection plugin @@ -165,7 +221,7 @@ jobs: -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 KAMINO_RUN_ID -e MOLECULE_LANES \ - "$CONTROLLER_IMAGE" scripts/run_molecule_in_ci_image.sh <<< "$selected" + "$CONTROLLER_IMAGE" scripts/run_molecule_in_ci_image.sh <<< "$SELECTED" # A cancelled run can leave its containers running when the docker client is killed. - name: Remove this run's containers @@ -178,3 +234,36 @@ jobs: for id in $ids; do docker rm -f "$id" >/dev/null || true; done left="$(docker ps -aq --filter "label=net.rkdr.mortis.molecule-run=$KAMINO_RUN_ID")" if [ -n "$left" ]; then echo "::error::could not remove ${left//$'\n'/ }"; exit 1; fi + + result: + name: Result + needs: [select, scenarios] + # always(): otherwise a failed select would skip this job, and Gitea counts a skipped job as + # passing. The guard is select's, so a fork pull request skips all three jobs alike and the run + # step below never sees a select skipped by it. + if: >- + always() && + github.repository == 'mortis/kamino' && + (github.event_name != 'pull_request' || + github.event.pull_request.head.repo.full_name == github.repository) + runs-on: kamino-docker + timeout-minutes: 5 + # Any small image does; the controller pin is reused so there is no other pin to bump. + container: + image: git.rkdr.net/mortis/molecule-controller:0.1.1@sha256:94af071ecae858016f9a61afa6e45f8344f8fef7d22d1fe899e05f5f48f756e8 + steps: + - name: Check the select and scenarios jobs + env: + SELECT_RESULT: ${{ needs.select.result }} + SCENARIOS_RESULT: ${{ needs.scenarios.result }} + SELECTED: ${{ needs.select.outputs.scenarios }} + run: | + if [ "$SELECT_RESULT" != success ]; then + echo "::error::select ended as $SELECT_RESULT"; exit 1 + fi + # A skip is a pass only for an empty selection: a cancelled or failed run is not. + if [ "$SCENARIOS_RESULT" = skipped ] && [ -z "$SELECTED" ]; then + echo "No scenario selected." + elif [ "$SCENARIOS_RESULT" != success ]; then + echo "::error::scenarios ended as $SCENARIOS_RESULT"; exit 1 + fi diff --git a/docs/contributing/maintaining.md b/docs/contributing/maintaining.md index 3fbf6e2..bfcdbf2 100644 --- a/docs/contributing/maintaining.md +++ b/docs/contributing/maintaining.md @@ -56,10 +56,10 @@ Every secret the workflows in [.gitea/workflows/](../../.gitea/workflows/) refer A checklist, not rules: what the repository and organisation settings should be. The maintainer applies them and checks them against this list after any change. -- Branch protection on `main`: required checks Lint, Build and Molecule; zero required approvals; - "Require approval from code owners"; "Dismiss stale approvals"; block on rejected and on official - review requests; block on an outdated branch; administrators cannot override; the approvals - allowlist is the maintainer. +- Branch protection on `main`: required checks Lint, Build and `Molecule / Result (pull_request)`; + zero required approvals; "Require approval from code owners"; "Dismiss stale approvals"; block + on rejected and on official review requests; block on an outdated branch; administrators cannot + override; the approvals allowlist is the maintainer. - Merge allowlist on `main`: the maintainer, each trusted contributor and the Renovate bot. - Push allowlist on `release/*`: the maintainer; no rule for `renovate/*`. - Tag protection on `v*`, with the maintainer on its allowlist. diff --git a/tests/scripts/test_run_molecule_scenarios.py b/tests/scripts/test_run_molecule_scenarios.py index b1f32a9..8a9c235 100644 --- a/tests/scripts/test_run_molecule_scenarios.py +++ b/tests/scripts/test_run_molecule_scenarios.py @@ -355,7 +355,7 @@ class RunMoleculeScenariosTest(unittest.TestCase): def test_the_default_time_limit_is_inside_the_job_timeout(self): # a limit past the job's own would let a hang take the job and every log with it - timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["molecule"][ + timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["scenarios"][ "timeout-minutes" ] limit = re.findall(r"MOLECULE_SCENARIO_TIMEOUT:-(\d+)\}", SCRIPT.read_text()) @@ -502,7 +502,7 @@ class ScenarioPlatformsTest(unittest.TestCase): def test_the_sweep_spares_containers_younger_than_the_job_timeout(self): # a shorter bound would remove the containers of a run still going - timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["molecule"][ + timeout = yaml.safe_load(WORKFLOW.read_text())["jobs"]["scenarios"][ "timeout-minutes" ] run = step_run("Remove the containers earlier runs left") @@ -519,12 +519,92 @@ class LanesInputTest(unittest.TestCase): # yaml reads the `on:` key as True lanes = workflow[True]["workflow_dispatch"]["inputs"]["lanes"] self.assertEqual((lanes["type"], lanes["default"]), ("string", "")) - steps = workflow["jobs"]["molecule"]["steps"] + steps = workflow["jobs"]["scenarios"]["steps"] step = next(s for s in steps if s.get("name") == "Run the scenarios") self.assertEqual(step["env"]["MOLECULE_LANES"], "${{ inputs.lanes }}") self.assertRegex(step["run"], r"docker run [^<]*-e MOLECULE_LANES\b") +class WorkflowJobsTest(unittest.TestCase): + """A pull request that selects no scenario takes no Molecule runner slot.""" + + JOBS = yaml.safe_load(WORKFLOW.read_text())["jobs"] + + def result(self, select, scenarios, selected): + """The exit code of the result job's check for those needs results and that selection.""" + (step,) = self.JOBS["result"]["steps"] + env = dict( + os.environ, + SELECT_RESULT=select, + SCENARIOS_RESULT=scenarios, + SELECTED=selected, + ) + return subprocess.run( + ["bash", "-e", "-c", step["run"]], + check=False, + env=env, + capture_output=True, + ).returncode + + def test_three_jobs_each_on_its_runner(self): + self.assertEqual( + {name: job["runs-on"] for name, job in self.JOBS.items()}, + { + "select": "kamino-docker", + "scenarios": ["kamino-molecule"], + "result": "kamino-docker", + }, + ) + + def test_only_the_scenarios_job_runs_on_the_host(self): + # select and result need no Docker daemon, so they take no Molecule runner slot + self.assertIn("container", self.JOBS["select"]) + self.assertIn("container", self.JOBS["result"]) + self.assertNotIn("container", self.JOBS["scenarios"]) + + def test_every_job_has_the_fork_guard(self): + guard = self.JOBS["select"]["if"] + self.assertIn("github.repository == 'mortis/kamino'", guard) + for name, job in self.JOBS.items(): + self.assertTrue(job["if"].endswith(guard), name) + + def test_the_scenarios_run_only_for_a_selection(self): + job = self.JOBS["scenarios"] + self.assertEqual(job["needs"], "select") + self.assertTrue(job["if"].startswith("needs.select.outputs.scenarios != '' &&")) + self.assertEqual( + self.JOBS["select"]["outputs"]["scenarios"], + "${{ steps.select.outputs.scenarios }}", + ) + step = next(s for s in job["steps"] if s.get("name") == "Run the scenarios") + self.assertEqual( + step["env"]["SELECTED"], "${{ needs.select.outputs.scenarios }}" + ) + self.assertIn('run_molecule_in_ci_image.sh <<< "$SELECTED"', step["run"]) + + def test_the_result_runs_whatever_the_others_ended_as(self): + job = self.JOBS["result"] + self.assertEqual(job["needs"], ["select", "scenarios"]) + self.assertTrue(job["if"].startswith("always() &&")) + + def test_the_result_passes_a_run_or_an_empty_selection_only(self): + self.assertEqual( + self.result("success", "success", "roles/a/molecule/default"), 0 + ) + self.assertEqual(self.result("success", "skipped", ""), 0) + self.assertNotEqual( + self.result("success", "skipped", "roles/a/molecule/default"), 0 + ) + self.assertNotEqual( + self.result("success", "failure", "roles/a/molecule/default"), 0 + ) + self.assertNotEqual( + self.result("success", "cancelled", "roles/a/molecule/default"), 0 + ) + self.assertNotEqual(self.result("failure", "skipped", ""), 0) + self.assertNotEqual(self.result("skipped", "skipped", ""), 0) + + class ScenarioSequenceTest(unittest.TestCase): """A role scenario previews the fresh host and the configured host with molecule's check step.""" diff --git a/tests/scripts/test_select_molecule_scenarios.py b/tests/scripts/test_select_molecule_scenarios.py index eec4106..9fe5434 100644 --- a/tests/scripts/test_select_molecule_scenarios.py +++ b/tests/scripts/test_select_molecule_scenarios.py @@ -678,13 +678,31 @@ class WorkflowPinsTest(unittest.TestCase): def test_the_workflow_has_each_pin_where_the_selector_looks(self): for key in ("CONTROLLER_IMAGE", "MOLECULE_IMAGE", "MOLECULE_IMAGE_2604"): - self.assertEqual(self.edited(self.pin(key), self.bumped(key)), {key}, key) + old, new = ( + f"{key}: >-\n {v}" for v in (self.pin(key), self.bumped(key)) + ) + self.assertEqual(self.edited(old, new), {key}, key) def test_the_workflow_runs_in_the_controller_image_not_ci(self): # A ci pin bump must touch only Lint and Build, which IGNORED lists (ADR 0003). self.assertIn("/mortis/molecule-controller:", self.pin("CONTROLLER_IMAGE")) self.assertNotIn("/mortis/ci:", self.WORKFLOW) + def test_every_controller_pin_is_the_same(self): + # container.image cannot read env, so the select and result jobs repeat CONTROLLER_IMAGE + jobs = yaml.safe_load(self.WORKFLOW)["jobs"] + pins = [ + jobs["select"]["container"]["image"], + self.pin("CONTROLLER_IMAGE"), + jobs["result"]["container"]["image"], + ] + self.assertEqual(len(set(pins)), 1, pins) + self.assertEqual(self.WORKFLOW.count("/mortis/molecule-controller:"), len(pins)) + # Renovate moves all three, which the selector reads as "any other change": every + # scenario, as for CONTROLLER_IMAGE alone. + bumped = self.WORKFLOW.replace(pins[0], self.bumped("CONTROLLER_IMAGE")) + self.assertIsNone(sel.pin_changes(self.WORKFLOW, bumped)) + def test_comments_and_blank_lines_change_nothing(self): self.assertEqual(self.edited("# Behavioural tests", "# Other words"), set()) self.assertEqual(self.edited("\njobs:\n", "\n\n\njobs:\n"), set())