Merge pull request 'ci(molecule): run scenarios in four lanes and drop molecule's trailing destroy' (#303) from ci/molecule-parallel-scenarios into main
Build / build (push) Successful in 20s
Lint / lint (push) Successful in 1m5s
Molecule / molecule (push) Successful in 11m54s

Reviewed-on: #303
Reviewed-by: Defame1297 <[email protected]>
This commit was merged in pull request #303.
This commit is contained in:
Defame1297 committed 2026-11-23 07:22:22 +00:00
commit 344adbfb7a
19 files changed
+499 -122

No files matched your search

+14 -8
View File
@@ -84,18 +84,24 @@ issue.
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.** 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 destroy
its instances, and two runs would collide on the same names. *Held:* review.
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.
- **Molecule tests the pull request's pins, as Lint and Build do.** *Why:* the pull request that
raises the ansible-core floor must be behaviour-tested on the new core before it automerges.
*Held:* aspirational until #225 runs Molecule from the `ci` image with the pin comparison
against `/opt/ci-pins.sha256`; today it runs from the runner's own venv.
- **Every scenario sets `scenario.test_sequence` to molecule's default minus the leading
`destroy`;** copy it into a new scenario. *Why:* the workflow clears stale containers first,
and the molecule state lives in the job's own `ANSIBLE_HOME`, so a killed run leaves none
behind. *Held:* review.
- **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.
- **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
+12 -39
View File
@@ -44,10 +44,11 @@ permissions:
# 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. Scenarios use fixed container names 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 a lock or a shared
# group again.
# 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.
concurrency:
group: molecule-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
@@ -127,10 +128,9 @@ jobs:
echo "KAMINO_COLLECTIONS=$dest" >> "$GITHUB_ENV"
# 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.
# molecule test destroys its instance on success and on failure; a cancelled run is killed
# before it can, so the step first removes what such a run left, since the next run may not
# select the same scenarios.
# explains the rules); a push to main 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.
- name: Run the scenarios
working-directory: ac/ansible_collections/mortis/kamino
env:
@@ -148,12 +148,11 @@ jobs:
# molecule calls ansible-config and ansible-playbook by name
export PATH="$MOLECULE_VENV/bin:$PATH"
# The collection under test first, then the pinned collections the roles use. molecule also
# installs the collection under test into ANSIBLE_HOME; keep that inside the
# job tree so no run resolves a copy another run left in the runner user's
# home (the version stays 0.1.0, so a stale copy would look current). The rm
# installs the collection under test into ANSIBLE_HOME, which the run script gives each
# scenario inside the job tree, so no run resolves a copy another run left in the runner
# user's home (the version stays 0.1.0, so a stale copy would look current). The rm
# clears a copy left there by runs before this was set.
ac_root="$(cd ../../.. && pwd)"
export ANSIBLE_HOME="$ac_root/.ansible"
export ANSIBLE_COLLECTIONS_PATH="$ac_root:$KAMINO_COLLECTIONS"
rm -rf "$HOME/.ansible/collections/ansible_collections/mortis"
# The selector comes from the base branch, so a pull request cannot edit the rules it is
@@ -169,30 +168,4 @@ jobs:
echo "::notice::no base copy of $sel; running this checkout's copy"
fi
selected="$(python3 -I "$sel" "$BASE_REF")" || exit 1
failed=""
ran=0
while IFS= read -r dir; do
[ -n "$dir" ] || continue
name="$(basename "$dir")"
case "$dir" in
extensions/*)
label="$name"
echo "::group::molecule test: $label"
molecule test -s "$name" </dev/null || failed="$failed $label"
;;
*)
role="${dir#roles/}"
role="${role%%/*}"
label="$role/$name"
echo "::group::molecule test: $label"
(cd "roles/$role" && molecule test -s "$name" </dev/null) || failed="$failed $label"
;;
esac
ran=$((ran + 1))
echo "::endgroup::"
done <<< "$selected"
echo "Scenarios run: $ran"
# A scenario that swallowed the rest of the list must not pass quietly.
want="$(grep -c . <<< "$selected" || true)"
test "$ran" -eq "$want" || { echo "::error::ran $ran of $want selected scenarios"; exit 1; }
test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
scripts/run_molecule_scenarios.sh "$ac_root/molecule-runs" <<< "$selected"
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -40,4 +39,3 @@ scenario:
- check
- verify
- cleanup
- destroy
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -27,10 +27,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -42,4 +41,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -36,10 +36,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -51,4 +50,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -44,10 +44,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -59,4 +58,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -26,10 +26,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -41,4 +40,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -32,10 +32,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -47,4 +46,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -46,10 +46,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -61,4 +60,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+3 -5
View File
@@ -25,10 +25,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -40,4 +39,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
@@ -33,10 +33,9 @@ provisioner:
verifier:
name: ansible
scenario:
# molecule's default sequence minus its first destroy: the workflow removes what a killed run
# left before any scenario starts, so that destroy only waits out the
# driver's 5 s poll on a container that is not there. After an aborted local run, run
# `molecule destroy` yourself.
# 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.
test_sequence:
- dependency
- cleanup
@@ -48,4 +47,3 @@ scenario:
- side_effect
- verify
- cleanup
- destroy
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
# The Molecule workflow's "Run the scenarios" step: `molecule test` for each scenario directory on
# stdin, MOLECULE_LANES (default 4) at a time, each with its own log and ANSIBLE_HOME under
# <work-dir>/<n>/ (molecule reinstalls the collection there with --force). Exit 1 on a failure.
#
# scripts/run_molecule_scenarios.sh <work-dir> < scenario-dirs
set -euo pipefail
lanes="${MOLECULE_LANES:-4}"
if ! [[ "$lanes" =~ ^[1-9][0-9]*$ ]]; then
echo "MOLECULE_LANES must be a positive integer, not '$lanes'" >&2
exit 2
fi
if [ "$#" -ne 1 ]; then
echo "usage: $0 <work-dir> < scenario-dirs" >&2
exit 2
fi
work="$1"
label_of() {
case "$1" in
extensions/*) echo "${1##*/}" ;;
*) local role="${1#roles/}"; echo "${role%%/*}/${1##*/}" ;;
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.
# python3 is the molecule venv's, with PyYAML.
remove_instances() {
local names ids
local py='import sys, yaml; print(*(p["name"] for p in yaml.safe_load(open(sys.argv[1]))["platforms"]))'
names="$(python3 -I -c "$py" "$1/molecule.yml")" || return 1
[ -n "$names" ] || return 1
# shellcheck disable=SC2046,SC2086 # names and ids are one word each
ids="$(docker ps -aq $(printf -- '--filter name=^/%s$ ' $names))" || return 1
# shellcheck disable=SC2086
if [ -n "$ids" ]; then docker rm -f $ids >/dev/null || return 1; fi
}
# Runs scenario $2 into $work/$1/. Its outcome is the rc file, which a lane that died lacks.
run_one() {
local out="$work/$1" dir="$2" start=$SECONDS rc=0
mkdir -p "$out/ansible"
(
export ANSIBLE_HOME="$out/ansible"
# a role scenario runs from its role's directory, as molecule expects
case "$dir" in roles/*) cd "${dir%/molecule/*}" || exit 1 ;; esac
molecule test -s "${dir##*/}"
) >"$out/log" 2>&1 </dev/null || rc=$?
if ! remove_instances "$dir" >>"$out/log" 2>&1; then
echo "could not remove the containers of $dir" >>"$out/log"
if [ "$rc" -eq 0 ]; then rc=1; fi
fi
echo "$((SECONDS - start))" >"$out/seconds"
echo "$rc" >"$out/rc"
echo "finished $(label_of "$dir"): exit $rc after $((SECONDS - start)) s"
}
dirs=()
while IFS= read -r dir; do
if [ -n "$dir" ]; then dirs+=("$dir"); fi
done
mkdir -p "$work"
# A cancelled job must not leave lanes behind that recreate containers after the next run's
# cleanup. A signal to this script stops each lane's tree so it cannot fork, then terminates it,
# with the whole group of any descendant that leads one: ansible's workers detach into their own.
# A kill of the step's process group reaches the lanes and molecule, not those detached workers.
kill_tree() {
local child leader=""
kill -STOP "$1" 2>/dev/null || return 0
# never a group this script or its caller is in: only one a descendant leads
if [ "$(ps -o pgid= -p "$1" | tr -d ' ')" = "$1" ] && [ "$1" != "$own_group" ]; then
leader=1
kill -STOP -- "-$1" 2>/dev/null || true
fi
for child in $(ps -o pid= --ppid "$1"); do kill_tree "$child"; done
if [ -n "$leader" ]; then
kill -TERM -- "-$1" 2>/dev/null || true
kill -CONT -- "-$1" 2>/dev/null || true
fi
kill -TERM "$1" 2>/dev/null || true
kill -CONT "$1" 2>/dev/null || true
}
stop_lanes() {
# a second signal must not abort the cleanup and leave a lane stopped
trap '' TERM INT HUP
local pid
for pid in $(jobs -rp); do kill_tree "$pid"; done
wait || true
exit "$1"
}
own_group="$(ps -o pgid= -p "$$" | tr -d ' ')"
trap 'stop_lanes 143' TERM
trap 'stop_lanes 130' INT
trap 'stop_lanes 129' HUP
for n in "${!dirs[@]}"; do
while [ "$(jobs -rp | wc -l)" -ge "$lanes" ]; do wait -n || true; done
run_one "$n" "${dirs[$n]}" </dev/null &
done
wait
failed=""
ran=0
times=""
for n in "${!dirs[@]}"; do
label="$(label_of "${dirs[$n]}")"
seconds="$(cat "$work/$n/seconds" 2>/dev/null || echo '?')"
times="$times $label: $seconds s"$'\n'
echo "::group::molecule test: $label ($seconds s)"
cat "$work/$n/log" 2>/dev/null || true
echo "::endgroup::"
if [ -f "$work/$n/rc" ]; then
ran=$((ran + 1))
if [ "$(cat "$work/$n/rc")" != 0 ]; then failed="$failed $label"; fi
fi
done
printf 'Scenarios run: %s\n%s' "$ran" "$times"
# A lane that died without a result must not pass quietly.
test "$ran" -eq "${#dirs[@]}" || { echo "::error::ran $ran of ${#dirs[@]} selected scenarios"; exit 1; }
test -z "$failed" || { echo "::error::Failed:$failed"; exit 1; }
@@ -0,0 +1,304 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Tests for scripts/run_molecule_scenarios.sh with stub molecule and docker on PATH.
Run with: python3 -m unittest discover -s tests/scripts
"""
import os
import pathlib
import re
import shutil
import signal
import subprocess
import tempfile
import time
import unittest
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
SCRIPT = REPO / "scripts" / "run_molecule_scenarios.sh"
WORKFLOW = REPO / ".gitea" / "workflows" / "molecule.yml"
# Records what each run saw, then behaves as STUB_<scenario label> asks: fail, sleep, hang (and
# record its pids), detach (as an ansible worker does, into its own process group, whose orphaned
# child no parent link reaches; record both), or read stdin (which must be empty).
MOLECULE_STUB = """#!/usr/bin/env bash
label="$(basename "$PWD")/$3"
[ "$PWD" = "$STUB_ROOT" ] && label="$3"
key="STUB_$(printf %s "$label" | tr -c 'A-Za-z0-9' _)"
echo "$label start $(date +%s.%N) home=$ANSIBLE_HOME cwd=$PWD args=$*" >> "$STUB_LOG"
echo "output of $label"
case "${!key:-}" in
fail) echo "$label end $(date +%s.%N)" >> "$STUB_LOG"; exit 2 ;;
sleep) sleep 1 ;;
hang) sleep 60 & echo "$$ $!" >> "$STUB_PIDS"; wait ;;
detach)
setsid bash -c '(sleep 60 & echo $! >> "$STUB_PIDS"); echo $$ >> "$STUB_PIDS"; exec sleep 60' &
wait ;;
stdin) echo "stdin of $label: [$(cat)]" ;;
esac
echo "$label end $(date +%s.%N)" >> "$STUB_LOG"
"""
# `ps` lists a container id per name filter; `rm` records the ids or fails on request.
DOCKER_STUB = """#!/usr/bin/env bash
echo "docker $*" >> "$STUB_DOCKER_LOG"
case "$1" in
ps) for a in "$@"; do case "$a" in name=*) n="${a#name=^/}"; echo "id-${n%$}" ;; esac; done ;;
rm) [ -z "${STUB_RM_FAIL:-}" ] || exit 1 ;;
esac
"""
PLATFORMS = {
"roles/alpha/molecule/default": ["alpha-instance"],
"roles/beta/molecule/default": ["beta-instance", "beta2-instance"],
"roles/beta/molecule/check_mode": ["beta-check-instance"],
"extensions/molecule/image-smoke": ["image-smoke"],
}
@unittest.skipUnless(shutil.which("bash"), "bash is required")
class RunMoleculeScenariosTest(unittest.TestCase):
def setUp(self):
self.tmp = pathlib.Path(tempfile.mkdtemp(prefix="kamino-runmol-")).resolve()
self.addCleanup(shutil.rmtree, self.tmp, True)
self.root = self.tmp / "kamino"
self.hung = []
for scenario, names in PLATFORMS.items():
d = self.root / scenario
d.mkdir(parents=True)
platforms = [{"name": 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()
for name, body in (("molecule", MOLECULE_STUB), ("docker", DOCKER_STUB)):
(bin_dir / name).write_text(body)
(bin_dir / name).chmod(0o755)
self.log = self.tmp / "molecule.log"
self.docker_log = self.tmp / "docker.log"
self.log.touch()
self.docker_log.touch()
self.env = {
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"HOME": str(self.tmp),
"STUB_ROOT": str(self.root),
"STUB_LOG": str(self.log),
"STUB_DOCKER_LOG": str(self.docker_log),
}
def run_script(self, scenarios, **env):
return subprocess.run(
["bash", str(SCRIPT), str(self.tmp / "work")],
cwd=self.root,
env={**self.env, **env},
input="".join(f"{s}\n" for s in scenarios),
capture_output=True,
text=True,
check=False,
)
def events(self):
"""{label: (start, end)} from the molecule stub's log."""
times = {}
for line in self.log.read_text().splitlines():
label, what, stamp = line.split()[:3]
times.setdefault(label, {})[what] = float(stamp)
return {k: (v["start"], v.get("end")) for k, v in times.items()}
def test_groups_follow_the_selection_order_with_times(self):
order = list(PLATFORMS)
proc = self.run_script(order, STUB_alpha_default="sleep")
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
groups = re.findall(
r"^::group::molecule test: (\S+) \((\d+) s\)$", proc.stdout, re.MULTILINE
)
self.assertEqual(
[g[0] for g in groups],
["alpha/default", "beta/default", "beta/check_mode", "image-smoke"],
)
self.assertGreaterEqual(int(groups[0][1]), 1)
self.assertEqual(proc.stdout.count("::endgroup::"), 4)
# each log sits inside its own group
body = proc.stdout.split("::group::molecule test: beta/default")[1].split(
"::endgroup::"
)[0]
self.assertIn("output of beta/default", body)
self.assertNotIn("output of alpha/default", body)
self.assertIn("Scenarios run: 4", proc.stdout)
self.assertIn(" image-smoke: ", proc.stdout)
def test_runs_in_lanes_and_isolates_each_scenario(self):
order = list(PLATFORMS)
stubs = {
f"STUB_{k}": "sleep"
for k in ("alpha_default", "beta_default", "image_smoke")
}
proc = self.run_script(order, MOLECULE_LANES="2", **stubs)
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
spans = self.events()
self.assertEqual(len(spans), 4)
running_at = [
sum(s <= t < e for s, e in spans.values()) for t, _end in spans.values()
]
self.assertEqual(max(running_at), 2, spans)
starts = [
line for line in self.log.read_text().splitlines() if " start " in line
]
homes = {re.search(r"home=(\S+)", s).group(1) for s in starts}
self.assertEqual(len(homes), 4)
check = next(s for s in starts if s.startswith("beta/check_mode "))
self.assertIn(
f"cwd={self.root / 'roles' / 'beta'} args=test -s check_mode", check
)
smoke = next(s for s in starts if s.startswith("image-smoke "))
self.assertIn(f"cwd={self.root} args=test -s image-smoke", smoke)
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()
for name in (n for names in PLATFORMS.values() for n in names):
self.assertIn(f"--filter name=^/{name}$", docker)
self.assertIn("docker rm -f id-beta-instance id-beta2-instance", docker)
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)
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)
self.assertIn(
"could not remove the containers of roles/alpha/molecule/default",
proc.stdout,
)
self.assertIn("::error::Failed: alpha/default\n", proc.stdout)
def test_a_scenario_without_a_result_fails_the_run(self):
# a lane that dies leaves no rc file: a file where the second scenario's work directory
# goes makes its lane fail before molecule starts
(self.tmp / "work").mkdir()
(self.tmp / "work" / "1").write_text("not a directory")
proc = self.run_script(
["roles/alpha/molecule/default", "roles/beta/molecule/default"]
)
self.assertEqual(proc.returncode, 1)
self.assertIn("::error::ran 1 of 2 selected scenarios", proc.stdout)
def test_lanes_must_be_a_positive_integer(self):
for lanes in ("0", "-1", "two", "04"):
proc = self.run_script(list(PLATFORMS), MOLECULE_LANES=lanes)
self.assertEqual(proc.returncode, 2, lanes)
self.assertIn("MOLECULE_LANES must be a positive integer", proc.stderr)
self.assertEqual(self.log.read_text(), "")
def start_hung_run(self, count=4, **stubs):
"""A run in its own process group whose molecule stubs hang, and the pids they record."""
pids = self.tmp / "pids"
pids.touch()
env = {**self.env, "STUB_PIDS": str(pids), "MOLECULE_LANES": "2"}
env.update(stubs or {"STUB_alpha_default": "hang", "STUB_beta_default": "hang"})
proc = subprocess.Popen(
["bash", str(SCRIPT), str(self.tmp / "work")],
cwd=self.root, env=env, stdin=subprocess.PIPE, text=True,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, start_new_session=True,
) # fmt: skip
self.addCleanup(lambda: proc.poll() is None and os.killpg(proc.pid, 9))
self.addCleanup(lambda: [os.kill(p, 9) for p in self.hung if alive(p)])
proc.stdin.write("".join(f"{s}\n" for s in PLATFORMS))
proc.stdin.close()
deadline = time.monotonic() + 10
while len(pids.read_text().split()) < count and time.monotonic() < deadline:
time.sleep(0.05)
self.hung = [int(p) for p in pids.read_text().split()]
self.assertEqual(len(self.hung), count)
return proc
def assert_all_gone(self, pids):
deadline = time.monotonic() + 5
while any(map(alive, pids)) and time.monotonic() < deadline:
time.sleep(0.05)
self.assertEqual([p for p in pids if alive(p)], [])
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
def test_a_terminated_run_kills_its_lanes(self):
proc = self.start_hung_run()
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=10), 143)
self.assert_all_gone(self.hung)
self.assertEqual(proc.stderr.read(), "")
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
@unittest.skipUnless(shutil.which("setsid"), "needs setsid")
def test_a_terminated_run_kills_detached_process_groups(self):
proc = self.start_hung_run(count=2, STUB_alpha_default="detach")
proc.send_signal(signal.SIGTERM)
self.assertEqual(proc.wait(timeout=10), 143)
self.assert_all_gone(self.hung)
@unittest.skipUnless(pathlib.Path("/proc/self").exists(), "needs /proc")
def test_a_killed_process_group_takes_its_lanes(self):
# a runner may cancel a step by killing its process group, which the script cannot trap
proc = self.start_hung_run()
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=10)
self.assert_all_gone(self.hung)
def test_an_empty_selection_runs_nothing(self):
proc = self.run_script(["", ""])
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
self.assertIn("Scenarios run: 0", proc.stdout)
self.assertEqual(self.log.read_text(), "")
def alive(pid):
"""Whether pid is a running process, not gone or a zombie."""
try:
stat = pathlib.Path(f"/proc/{pid}/stat").read_text()
except FileNotFoundError:
return False
return stat.rsplit(")", 1)[1].split()[0] != "Z"
def stale_filters():
"""The name filters of the workflow's stale-container cleanup, as docker matches /<name>."""
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)
class ScenarioPlatformNamesTest(unittest.TestCase):
"""The run script removes containers by literal platform name, and scenarios run side by side."""
def test_platform_names_are_literal_unique_and_cleared_before_a_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:
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.assertNotIn(
name, seen, f"{where} and {seen.get(name)} share {name}"
)
seen[name] = where
self.assertNotIn("destroy", data["scenario"]["test_sequence"], path)
if __name__ == "__main__":
unittest.main()