Files
Kamino/scripts/select_molecule_scenarios.py
T
Defame1297andClaude Opus 5.5 f4965db6f3
Build / build (pull_request) Successful in 12s
Lint / lint (pull_request) Successful in 1m17s
Molecule / molecule (pull_request) Successful in 11m34s
feat(_binary_update): add the internal binary update role
Swaps a staged, verified binary into place for a systemd service: refuse when nothing
executable is staged, then reload, stop and wait, back up the live binary, rename the
staged file over it, start and wait for active, and compare the reported version. A
failure after the stop restores this run's backup, starts the service again and fails
with a message that says whether the restore and the restart worked. Under --check the
waits and the version check are skipped, so a preview against a stopped service does
not fall into the rollback. The staged file is removed in every case.

The role is internal (ADR 0004 in the environment repository): called only by roles of
this Collection by FQCN, outside the public API, marked by the underscore, [INTERNAL]
in its meta and argument_specs, and a first task that refuses a call without a parent
role. traefik is its first caller and arrives in the same release.

Two molecule scenarios use stub binaries under a stub unit, without network: default
(successful bump and idempotence, a binary that cannot start, a binary that reports the
wrong version, nothing staged, a direct call, a first install) and check_mode (the bump
under molecule check against a stopped service changes nothing).

Lint: role-name is skipped (its regex rejects the leading underscore, as for
prometheus.prometheus roles/_common), meta has no role_name (schema[meta] uses the same
regex and cannot be skipped), and .ansible-lint-ignore lists the role's own files for
var-naming[no-role-prefix], which strips the underscore from the variable but not from
the role name and so cannot pass. The ignore file is kept out of the Collection build
and is on the scenario picker's IGNORED list. The README Roadmap no longer lists the role.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-20 19:00:19 +00:00

281 lines
10 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the molecule scenarios a run needs.
python3 -I scripts/select_molecule_scenarios.py [<base-ref>]
Prints one scenario directory per line (`extensions/molecule/<name>` or
`roles/<role>/molecule/<name>`), extensions first, then roles, each sorted. The molecule
workflow runs `molecule test` in each.
Only a pull request is narrowed, and only when <base-ref> is given and EVENT_NAME is
`pull_request`. Then the diff of <base-ref>...HEAD decides:
* a file under roles/<role>/ selects that role's scenarios, and those of every role that
uses it (below);
* a file on the IGNORED list (documentation, changelog, repository tooling that no
scenario reads) selects nothing;
* any other file selects every scenario.
A role uses another when any file under its directory names it as `mortis.kamino.<other>`
(an include_role, a scenario's prepare play, a comment). The relation is transitive: when
`a` names `b` and `b` names `c`, a change to `c` selects all three. The roles call each other
by that full name only (a test checks includes, imports, play `roles:` entries and meta
dependencies for a bare or templated role name), so the text search finds every use. It reads the
tree under test, not the base: a pull request that drops a use also changes the using role,
which then selects itself, and a role the pull request deletes or renames still counts as used
by the roles that name it. A shared file outside roles/<role>/ (a plugin) already selects
everything.
Every other case runs everything: a push, a manual dispatch, a scheduled run, no <base-ref>, 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.
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
nothing tested. A role whose directory is gone (the role was deleted) selects nothing.
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). A change to this file therefore selects everything
under the base copy's rules, because the file is not on the IGNORED list.
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
control characters in paths escaped so a crafted file name cannot inject a log command.
"""
import fnmatch
import os
import re
import subprocess
import sys
# Paths no scenario reads. A match is by fnmatch on the repository-relative path, where `*`
# also crosses `/`. Keep this list short and literal: anything not listed runs everything.
IGNORED = (
"docs/*",
"changelogs/*",
"LICENSES/*",
"README.md",
"CONTRIBUTING.md",
"SECURITY.md",
"GLOSSARY.md",
"CLAUDE.md",
"CHANGELOG.rst",
"COPYING",
"NOTICE",
"REUSE.toml",
"renovate.json",
".gitignore",
".yamllint",
".ansible-lint",
".ansible-lint-ignore",
".pre-commit-config.yaml",
"requirements-dev.txt",
"requirements-dev.lock",
"ruff.toml",
"apm.yml",
"apm.lock.yaml",
"tests/sanity/*",
"tests/scripts/*",
"images/*",
".gitea/actionlint.yaml",
".gitea/workflows/lint.yml",
".gitea/workflows/build.yml",
".gitea/workflows/image.yml",
".gitea/workflows/renovate.yml",
"scripts/bump_image_versions.py",
"scripts/check_bot_pr_diff.py",
"scripts/check_image_versions.py",
"scripts/check_tarball.py",
"scripts/ansible-lint.sh",
"scripts/ansible-test-sanity.sh",
"scripts/dev-setup.sh",
"scripts/reuse_lint.py",
)
def printable(text):
"""`text` with control characters (a newline in a file name) escaped, for a log line."""
return "".join(
c if c.isprintable() else c.encode("unicode_escape").decode("ascii")
for c in text
)
def discover(root="."):
"""Every scenario directory, extensions first, each group sorted."""
found = []
ext = os.path.join(root, "extensions", "molecule")
if os.path.isdir(ext):
for name in sorted(os.listdir(ext)):
if name.isprintable() and os.path.isfile(
os.path.join(ext, name, "molecule.yml")
):
found.append(f"extensions/molecule/{name}")
roles = os.path.join(root, "roles")
if os.path.isdir(roles):
for role in sorted(os.listdir(roles)):
mol = os.path.join(roles, role, "molecule")
if not os.path.isdir(mol):
continue
for name in sorted(os.listdir(mol)):
if (
role.isprintable()
and name.isprintable()
and os.path.isfile(os.path.join(mol, name, "molecule.yml"))
):
found.append(f"roles/{role}/molecule/{name}")
return found
ROLE_REFERENCE = re.compile(r"mortis\.kamino\.([A-Za-z0-9_]+)")
def users(root=".", gone=()):
"""Map each role to the roles whose files name it as mortis.kamino.<role>.
Self-references (a scenario converging its own role) are left out, and so are names that
are neither a role directory nor in `gone`: the changed roles, so that a role deleted or
renamed by the pull request still selects the roles that call it.
"""
base = os.path.join(root, "roles")
if not os.path.isdir(base):
return {}
roles = {r for r in os.listdir(base) if os.path.isdir(os.path.join(base, r))}
known = roles | set(gone)
used_by = {}
for role in roles:
for dirpath, _dirs, files in os.walk(os.path.join(base, role)):
for name in files:
try:
with open(os.path.join(dirpath, name), "rb") as f:
text = f.read().decode("utf-8", "ignore")
except OSError:
continue
for other in ROLE_REFERENCE.findall(text):
if other != role and other in known:
used_by.setdefault(other, set()).add(role)
return used_by
def with_users(roles, used_by):
"""`roles` plus every role that uses one of them, directly or through another."""
found = set(roles)
todo = list(roles)
while todo:
for user in used_by.get(todo.pop(), ()):
if user not in found:
found.add(user)
todo.append(user)
return found
def is_ignored(path):
return any(fnmatch.fnmatchcase(path, pattern) for pattern in IGNORED)
def select(all_scenarios, changed, root="."):
"""The scenarios `changed` (repository-relative paths) needs, and a one-line reason.
Raises ValueError when a changed role still exists but has no scenario.
"""
roles = set()
for path in changed:
if is_ignored(path):
continue
parts = path.split("/")
if len(parts) > 2 and parts[0] == "roles":
roles.add(parts[1])
continue
return list(all_scenarios), f"{printable(path)} can affect every scenario"
changed_roles = roles
roles = with_users(changed_roles, users(root, changed_roles))
chosen = [
s for s in all_scenarios if s.startswith("roles/") and s.split("/")[1] in roles
]
covered = {s.split("/")[1] for s in chosen}
bare = sorted(
r for r in roles - covered if os.path.isdir(os.path.join(root, "roles", r))
)
if bare:
raise ValueError(
"role without a molecule scenario (changed, or a user of a changed role): "
+ ", ".join(printable(r) for r in bare)
)
if roles:
reason = "only roles changed: " + ", ".join(
printable(r) for r in sorted(changed_roles)
)
if roles - changed_roles:
reason += "; their users: " + ", ".join(
printable(r) for r in sorted(roles - changed_roles)
)
else:
reason = "no change that a scenario reads"
return chosen, reason
def changed_paths(base_ref):
"""Paths changed in base_ref...HEAD; a rename counts as a delete plus an add."""
out = subprocess.run(
[
"git",
"diff",
"--name-only",
"--no-renames",
"-z",
f"{base_ref}...HEAD",
"--",
],
check=True,
capture_output=True,
).stdout
return [os.fsdecode(p) for p in out.split(b"\0") if p]
def main(argv, environ=None):
environ = os.environ if environ is None else environ
if len(argv) > 2:
print("usage: select_molecule_scenarios.py [<base-ref>]", file=sys.stderr)
return 2
base_ref = argv[1] if len(argv) == 2 else ""
scenarios = discover()
if not scenarios:
print("::error::no molecule scenario found", file=sys.stderr)
return 1
if environ.get("EVENT_NAME") != "pull_request" or not base_ref:
print(
f"::notice::Running all {len(scenarios)} scenarios (not a pull request)",
file=sys.stderr,
)
chosen = scenarios
else:
try:
changed = changed_paths(base_ref)
except (subprocess.CalledProcessError, OSError, UnicodeError) as exc:
print(
f"::warning::cannot diff against {printable(base_ref)} ({printable(str(exc))}); running all scenarios",
file=sys.stderr,
)
chosen = scenarios
else:
try:
chosen, reason = select(scenarios, changed)
except ValueError as exc:
print(f"::error::{exc}", file=sys.stderr)
return 1
print(
f"::notice::Running {len(chosen)} of {len(scenarios)} scenarios: {reason}",
file=sys.stderr,
)
for scenario in chosen:
print(scenario)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))