ci(molecule): skip the Molecule runner when no scenario is selected #503

Open
Claude wants to merge 3 commits from ci/433-skip-empty-molecule into main
pull from: ci/433-skip-empty-molecule
5 changed files with 274 additions and 37 deletions

No files matched your search

+14 -1
View File
@@ -72,11 +72,24 @@ 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, or `none`.
`scenarios` runs them on `kamino-molecule` and is skipped for `none` or an empty output.
`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
`none`, so a lost output fails it. 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.<role>`, transitively), none for a diff of only IGNORED paths, a failure for a
+116 -28
View File
@@ -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,82 @@ 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
# `none` marks an empty selection, so a lost or empty output fails result, never passes.
if [ -z "$selected" ]; then selected=none; fi
# One directory per line; a random delimiter, so no line of the list can end the value.
delim="scenarios-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
printf 'scenarios<<%s\n%s\n%s\n' "$delim" "$selected" "$delim" >> "$GITHUB_OUTPUT"
scenarios:
needs: select
# Skipped, not failed, when select fails, selects nothing (`none`) or loses its output (empty);
# result passes only the second.
if: >-
needs.select.outputs.scenarios != 'none' &&
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 +134,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 +194,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 `~<user>/.ansible/tmp`. The driver's connection plugin
@@ -165,7 +220,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 +233,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
# The controller pin again, so this job adds no pin of its own 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 select's `none`: an empty output means it was lost.
if [ "$SCENARIOS_RESULT" = skipped ] && [ "$SELECTED" = none ]; then
echo "No scenario selected."
elif [ "$SCENARIOS_RESULT" != success ]; then
echo "::error::scenarios ended as $SCENARIOS_RESULT"; exit 1
fi
+4 -4
View File
@@ -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.
+121 -3
View File
@@ -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,130 @@ 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(
# act runs a job container's step with sh when the step sets no shell
["sh", "-e", "-c", step["run"]],
check=False,
env=env,
capture_output=True,
).returncode
def written_output(self, selected):
"""The `scenarios` output select's run step writes for that selector output."""
step = next(s for s in self.JOBS["select"]["steps"] if s.get("id") == "select")
block = step["run"].split("|| exit 1\n", 1)[1]
with tempfile.TemporaryDirectory() as tmp:
out = pathlib.Path(tmp, "output")
subprocess.run(
["sh", "-e", "-c", 'selected="$1"\n' + block, "sh", selected],
check=True,
env=dict(os.environ, GITHUB_OUTPUT=str(out)),
)
lines = out.read_text().splitlines()
# GITHUB_OUTPUT's `name<<delimiter` form: the value is every line up to the delimiter
name, delim = lines[0].split("<<", 1)
self.assertEqual((name, lines[-1]), ("scenarios", delim))
self.assertNotIn(delim, lines[1:-1])
return "\n".join(lines[1:-1])
def test_select_writes_none_for_an_empty_selection(self):
self.assertEqual(self.written_output(""), "none")
def test_select_writes_the_selection_one_directory_per_line(self):
selected = "extensions/molecule/image-smoke\nroles/a/molecule/default"
self.assertEqual(self.written_output(selected), selected)
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 = (
"github.repository == 'mortis/kamino' && "
"(github.event_name != 'pull_request' || "
"github.event.pull_request.head.repo.full_name == github.repository)"
)
self.assertEqual(self.JOBS["select"]["if"], 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")
# false for `none` and for an empty or missing output alike
self.assertTrue(
job["if"].startswith(
"needs.select.outputs.scenarios != 'none' && "
"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_a_none_selection_only(self):
self.assertEqual(
self.result("success", "success", "roles/a/molecule/default"), 0
)
self.assertEqual(self.result("success", "skipped", "none"), 0)
# an empty output was lost, not an empty selection
self.assertNotEqual(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", "none"), 0)
self.assertNotEqual(self.result("skipped", "skipped", "none"), 0)
class ScenarioSequenceTest(unittest.TestCase):
"""A role scenario previews the fresh host and the configured host with molecule's check step."""
@@ -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())