feat(kvb-check-ansible): rank where an Ansible run spends its time
New skill with ansible_tasks.py: gaps, durations, kinds, kind and task rank a run's log by wall-clock gaps or profile_tasks lines; profile-report merges cProfile dumps of the controller and its forked workers (sitecustomize hook); bench-carrier and the bench playbook measure per-task overhead against variable size. kvb-code-tune hands its Ansible timing to it. 🎯 Fix: 92 % 💥 Break: 2 % 💸 Cost: new ⏱️ Time: new 🛡️ Security: 100 % 🏆 Score: 90 🚦 Gate: cost new, time new: cleared by the operator's commit word for kvb-check-ansible (2026-11-07) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8b0c287ada
commit
05cc891998
17 files changed
+1212
No files matched your search
@@ -0,0 +1,86 @@
|
||||
---
|
||||
name: kvb-check-ansible
|
||||
description: >
|
||||
Rank where an Ansible run spends its time from its log, profile the
|
||||
controller, bench per-task overhead. Trigger on a slow playbook or deploy.
|
||||
---
|
||||
|
||||
Where an Ansible run spends its time: its log, a controller profile, a bench.
|
||||
Report the script's lines with their log and range, never a guess. The
|
||||
script and the bench are light runs (`watch.py admit --kind test-nostack` of
|
||||
`kvb-org-organize`); a deploy to profile is heavy and goes through the
|
||||
`kvb-org-queue` skill.
|
||||
|
||||
## 1. Pick the log
|
||||
|
||||
- The newest log of the current code; an older one may time a task since
|
||||
replaced.
|
||||
- A log whose lines start with an ISO timestamp (GitHub Actions) times every
|
||||
task by wall clock. A local run needs
|
||||
`ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks`, streamed to a file.
|
||||
- One deploy among several: bound it with `--from` and `--to`, line numbers
|
||||
from `grep -n 'PLAY \['`.
|
||||
|
||||
## 2. Rank
|
||||
|
||||
```bash
|
||||
python3 ${CLAUDE_SKILL_DIR}/scripts/ansible_tasks.py gaps --log <log> --top 20
|
||||
```
|
||||
|
||||
| Subcommand | Prints |
|
||||
| --- | --- |
|
||||
| `gaps` | wall seconds and count per task name, then `TOTAL` |
|
||||
| `durations` | the same from `profile_tasks` `(h:mm:ss.sss)` lines |
|
||||
| `kinds` | per kind (ran, skipped, included, other): count, sum, mean, buckets `<0.25` to `>=2` s |
|
||||
| `kind --kind <kind>` | per task name, that kind only |
|
||||
| `task --needle <text>` | every occurrence: start line, seconds, kind |
|
||||
|
||||
`kinds`, `kind` and `task` read wall gaps when a header carries a timestamp,
|
||||
else `profile_tasks` lines; `--source wall|profile` forces one. A task runs
|
||||
from its header to the next header or `PLAY RECAP`. `--json` prints JSON;
|
||||
exit 2 means nothing measurable in the range.
|
||||
|
||||
Rank by sum, a name's cost times its count: 400 skips of 0.3 s outweigh one
|
||||
60 s download.
|
||||
|
||||
## 3. Profile the controller
|
||||
|
||||
A skipped task does no work on any host; its time is controller overhead
|
||||
(templating, variable merging, one worker fork per task). Profile only when
|
||||
`kinds` shows it: a `skipped` mean of 0.1 s or more, or `skipped` and
|
||||
`included` together holding 10 % of the sum or more.
|
||||
|
||||
```bash
|
||||
ANSIBLE_PROFILE_DIR=<new dir> PYTHONPATH=${CLAUDE_SKILL_DIR}/scripts/profile ansible-playbook <the run's arguments>
|
||||
python3 ${CLAUDE_SKILL_DIR}/scripts/ansible_tasks.py profile-report --dir <new dir> --top 30
|
||||
```
|
||||
|
||||
- `sitecustomize.py` profiles only a process named `ansible-playbook`: the
|
||||
controller into `main-<pid>.prof`, each forked worker into
|
||||
`worker-<pid>.prof`; without `ANSIBLE_PROFILE_DIR` into
|
||||
`$TMPDIR/ansible-profile`.
|
||||
- The report merges every file of the directory: a new one per run.
|
||||
- `PYTHONPATH` must reach the controller's interpreter (virtualenv,
|
||||
container) and shadows a distribution's own `sitecustomize`.
|
||||
- A profiled run is slower: compare profiles with profiles, never its wall
|
||||
clock with an unprofiled run.
|
||||
|
||||
## 4. Bench the per-task overhead
|
||||
|
||||
```bash
|
||||
python3 ${CLAUDE_SKILL_DIR}/scripts/ansible_tasks.py bench-carrier --kb <size> --out <dir>/carrier.json
|
||||
ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks ansible-playbook -i ${CLAUDE_SKILL_DIR}/bench/hosts.yml ${CLAUDE_SKILL_DIR}/bench/bench.yml -e bench_count=200 -e bench_carrier_file=<dir>/carrier.json > <dir>/bench-<size>.log 2>&1
|
||||
python3 ${CLAUDE_SKILL_DIR}/scripts/ansible_tasks.py kinds --log <dir>/bench-<size>.log
|
||||
```
|
||||
|
||||
Each item includes one skipped and one run `debug` task on localhost. Run
|
||||
once without `bench_carrier_file` and once per `<size>` in KiB, up to the
|
||||
run's biggest variable; the change of the `skipped` mean is that fact's cost
|
||||
per task. Without `ansible.posix`, divide the wall-time difference of
|
||||
`bench_count=0` and `bench_count=200` by 400.
|
||||
|
||||
## Report
|
||||
|
||||
Per finding: subcommand, log and range, its line as printed, and the saving
|
||||
ceiling, count times the measured cost per task. Hand the ranking to the
|
||||
`kvb-code-tune` loop.
|
||||
@@ -0,0 +1,12 @@
|
||||
- name: Bench the controller cost per task
|
||||
hosts: bench
|
||||
gather_facts: false
|
||||
tasks:
|
||||
- name: Park the synthetic fact
|
||||
ansible.builtin.set_fact:
|
||||
bench_carrier: "{{ lookup('ansible.builtin.file', bench_carrier_file) | from_json }}"
|
||||
when: bench_carrier_file | default('') | length > 0
|
||||
|
||||
- name: Include one skipped and one run task per item
|
||||
ansible.builtin.include_tasks: one.yml
|
||||
loop: "{{ range(0, bench_count | int) | list }}"
|
||||
@@ -0,0 +1,5 @@
|
||||
all:
|
||||
hosts:
|
||||
bench:
|
||||
ansible_connection: local
|
||||
ansible_python_interpreter: "{{ ansible_playbook_python }}"
|
||||
@@ -0,0 +1,8 @@
|
||||
- name: Skipped
|
||||
ansible.builtin.debug:
|
||||
msg: never
|
||||
when: false
|
||||
|
||||
- name: Ran
|
||||
ansible.builtin.debug:
|
||||
msg: once
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Write the synthetic JSON fact the bench playbook parks on its host.
|
||||
|
||||
Args:
|
||||
size: exact size of the JSON text in bytes.
|
||||
kb: exact size of the written file in KiB.
|
||||
out: file the fact goes to.
|
||||
|
||||
Output:
|
||||
A dict of nested service entries, many small objects as real inventories carry them,
|
||||
filled up to the exact size by one pad string. write returns a (report, lines) pair.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ENTRY = {
|
||||
"services": {
|
||||
f"s{service}": {
|
||||
"image": "x" * 20,
|
||||
"version": "1.2.3",
|
||||
"env": {f"K{key}": "v" * 10 for key in range(10)},
|
||||
}
|
||||
for service in range(5)
|
||||
}
|
||||
}
|
||||
PAD = "pad"
|
||||
|
||||
|
||||
def carrier(size: int) -> dict:
|
||||
value = len(json.dumps(ENTRY))
|
||||
room = len(f', "{PAD}": ""')
|
||||
fact: dict[str, object] = {}
|
||||
used = len("{}")
|
||||
while True:
|
||||
key = f"entry-{len(fact)}"
|
||||
grow = len(", ") * bool(fact) + len(json.dumps(key)) + len(": ") + value
|
||||
if used + grow + room > size:
|
||||
break
|
||||
fact[key] = ENTRY
|
||||
used += grow
|
||||
fact[PAD] = "p" * (size - used - len(", ") * bool(fact) - len(f'"{PAD}": ""'))
|
||||
return fact
|
||||
|
||||
|
||||
def write(kb: int, out: Path) -> tuple[dict, list[str]]:
|
||||
fact = carrier(kb * 1024)
|
||||
text = json.dumps(fact)
|
||||
out.write_text(text, encoding="ascii")
|
||||
report = {"out": str(out), "bytes": len(text), "entries": len(fact) - 1}
|
||||
return report, [f"{report['out']}\t{report['bytes']} bytes\t{report['entries']} entries"]
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Parse Ansible output into timed task occurrences.
|
||||
|
||||
Args:
|
||||
path: the Ansible output to read.
|
||||
first, last: first and last line to read, 1-based and inclusive; None reads to that end.
|
||||
source: wall (ISO timestamps) or profile (profile_tasks); None picks wall when a header
|
||||
in range carries a timestamp, else profile.
|
||||
|
||||
Output:
|
||||
A task lasts from its TASK or RUNNING HANDLER header to the next header or PLAY RECAP;
|
||||
profile_tasks prints that duration under the next header. Its kind is ran on an ok,
|
||||
changed, failed or fatal result line, else skipped on a skipping line, else included
|
||||
on an included line, else other. A stamp without zone counts as UTC. Unmeasurable
|
||||
names what the range lacks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
HEADER = re.compile(r"(?:TASK|RUNNING HANDLER) \[(?P<name>.*)\][\s*]*$")
|
||||
RECAP = re.compile(r"PLAY RECAP \*")
|
||||
STAMP = re.compile(
|
||||
r"^(?P<day>\d{4}-\d{2}-\d{2})[T ](?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})"
|
||||
r"(?:[.,](?P<fraction>\d+))?(?P<zone>Z|[+-]\d{2}:?\d{2})? ?"
|
||||
)
|
||||
ELAPSED = re.compile(r"\((?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+(?:\.\d+)?)\)")
|
||||
ANSI = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")
|
||||
RESULTS = (
|
||||
("ran", re.compile(r"^\s*(?:ok|changed|failed|fatal): \[")),
|
||||
("skipped", re.compile(r"^\s*skipping: \[")),
|
||||
("included", re.compile(r"^\s*included: ")),
|
||||
)
|
||||
OTHER = "other"
|
||||
KINDS = (*(kind for kind, _ in RESULTS), OTHER)
|
||||
SOURCES = ("wall", "profile")
|
||||
|
||||
Rows = Iterator[tuple[int, float | None, str]]
|
||||
|
||||
|
||||
class Unmeasurable(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoStamps(Unmeasurable):
|
||||
pass
|
||||
|
||||
|
||||
class Task:
|
||||
def __init__(self, name: str, line: int, start: float | None) -> None:
|
||||
self.name = name
|
||||
self.line = line
|
||||
self.start = start
|
||||
self.seconds = 0.0
|
||||
self.seen: set[str] = set()
|
||||
|
||||
def note(self, content: str) -> None:
|
||||
self.seen.update(kind for kind, pattern in RESULTS if pattern.search(content))
|
||||
|
||||
@property
|
||||
def kind(self) -> str:
|
||||
return next((kind for kind, _ in RESULTS if kind in self.seen), OTHER)
|
||||
|
||||
|
||||
def offset(zone: str | None) -> int:
|
||||
if zone is None or zone == "Z":
|
||||
return 0
|
||||
digits = zone[1:].replace(":", "")
|
||||
seconds = int(digits[:2]) * 3600 + int(digits[2:]) * 60
|
||||
return -seconds if zone.startswith("-") else seconds
|
||||
|
||||
|
||||
def epoch(match: re.Match[str]) -> float:
|
||||
year, month, day = (int(part) for part in match["day"].split("-"))
|
||||
whole = calendar.timegm((year, month, day, int(match["hour"]), int(match["minute"]), int(match["second"])))
|
||||
fraction = float(f"0.{match['fraction']}") if match["fraction"] else 0.0
|
||||
return whole + fraction - offset(match["zone"])
|
||||
|
||||
|
||||
def split_stamp(text: str) -> tuple[float | None, str]:
|
||||
match = STAMP.match(text)
|
||||
if match is None:
|
||||
return None, text
|
||||
return epoch(match), text[match.end():]
|
||||
|
||||
|
||||
def read(path: Path, first: int | None, last: int | None) -> Rows:
|
||||
with path.open(encoding="utf-8-sig", errors="replace") as handle:
|
||||
for number, raw in enumerate(handle, 1):
|
||||
if first is not None and number < first:
|
||||
continue
|
||||
if last is not None and number > last:
|
||||
return
|
||||
stamp, content = split_stamp(ANSI.sub("", raw.rstrip("\r\n")))
|
||||
yield number, stamp, content
|
||||
|
||||
|
||||
def boundary(content: str) -> tuple[bool, str | None]:
|
||||
header = HEADER.search(content)
|
||||
if header is not None:
|
||||
return True, header["name"]
|
||||
return RECAP.search(content) is not None, None
|
||||
|
||||
|
||||
def wall(rows: Rows) -> list[Task]:
|
||||
done: list[Task] = []
|
||||
current: Task | None = None
|
||||
stamped = False
|
||||
for number, stamp, content in rows:
|
||||
found, name = boundary(content)
|
||||
if not found:
|
||||
if current is not None:
|
||||
current.note(content)
|
||||
continue
|
||||
if stamp is None:
|
||||
continue
|
||||
stamped = True
|
||||
if current is not None:
|
||||
current.seconds = stamp - current.start
|
||||
done.append(current)
|
||||
current = None if name is None else Task(name, number, stamp)
|
||||
if not stamped:
|
||||
raise NoStamps("no TASK, RUNNING HANDLER or PLAY RECAP header with an ISO timestamp in range")
|
||||
if not done:
|
||||
raise Unmeasurable("no task closed by a later timestamped header in range")
|
||||
return done
|
||||
|
||||
|
||||
def elapsed(match: re.Match[str]) -> float:
|
||||
return int(match["hours"]) * 3600 + int(match["minutes"]) * 60 + float(match["seconds"])
|
||||
|
||||
|
||||
def profile(rows: Rows) -> list[Task]:
|
||||
done: list[Task] = []
|
||||
current: Task | None = None
|
||||
waiting: Task | None = None
|
||||
for number, _, content in rows:
|
||||
found, name = boundary(content)
|
||||
if found:
|
||||
if current is not None:
|
||||
waiting = current
|
||||
current = None if name is None else Task(name, number, None)
|
||||
continue
|
||||
duration = ELAPSED.search(content)
|
||||
if duration is not None and waiting is not None:
|
||||
waiting.seconds = elapsed(duration)
|
||||
done.append(waiting)
|
||||
waiting = None
|
||||
elif current is not None:
|
||||
current.note(content)
|
||||
if not done:
|
||||
raise Unmeasurable(
|
||||
"no profile_tasks (h:mm:ss.sss) duration under a header in range; "
|
||||
"enable the ansible.posix.profile_tasks callback, or use gaps on a timestamped log"
|
||||
)
|
||||
return done
|
||||
|
||||
|
||||
def tasks(path: Path, first: int | None, last: int | None, source: str | None) -> tuple[str, list[Task]]:
|
||||
if source == "profile":
|
||||
return source, profile(read(path, first, last))
|
||||
if source == "wall":
|
||||
return source, wall(read(path, first, last))
|
||||
try:
|
||||
return "wall", wall(read(path, first, last))
|
||||
except NoStamps:
|
||||
return "profile", profile(read(path, first, last))
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Merge the main and worker cProfile files of an ansible-playbook run.
|
||||
|
||||
Args:
|
||||
directory: profile directory; the default of profile/sitecustomize.py when None.
|
||||
top: functions per ranking.
|
||||
|
||||
Output:
|
||||
A (report, lines) pair: per role (main, worker) the profile count, own seconds and the
|
||||
top functions by cumulative and by own time. Unmeasurable when the directory holds no
|
||||
profile or an unreadable one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import pstats
|
||||
from pathlib import Path
|
||||
|
||||
import ansible_log
|
||||
|
||||
PROFILER = Path(__file__).resolve().parent / "profile" / "sitecustomize.py"
|
||||
ROLES = ("main", "worker")
|
||||
TOTAL_TIME = 2
|
||||
CUMULATIVE_TIME = 3
|
||||
|
||||
|
||||
def default_dir() -> Path:
|
||||
spec = importlib.util.spec_from_file_location("ansible_profile_site", PROFILER)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return Path(module.profile_dir())
|
||||
|
||||
|
||||
def hottest(stats: pstats.Stats, field: int, top: int) -> list[dict]:
|
||||
rows = sorted(stats.stats.items(), key=lambda item: -item[1][field])[:top]
|
||||
return [
|
||||
{"function": pstats.func_std_string(func), "calls": calls, "tottime": round(own, 6), "cumtime": round(cumulative, 6)}
|
||||
for func, (_, calls, own, cumulative, _) in rows
|
||||
]
|
||||
|
||||
|
||||
def merged(directory: Path, top: int) -> dict[str, dict]:
|
||||
roles: dict[str, dict] = {}
|
||||
for role in ROLES:
|
||||
files = sorted(directory.glob(f"{role}-*.prof"))
|
||||
if not files:
|
||||
continue
|
||||
try:
|
||||
stats = pstats.Stats(*(str(file) for file in files))
|
||||
except (EOFError, TypeError, ValueError) as error:
|
||||
raise ansible_log.Unmeasurable(f"unreadable profile in {directory}: {error}") from None
|
||||
roles[role] = {
|
||||
"profiles": len(files),
|
||||
"seconds": round(stats.total_tt, 3),
|
||||
"cumulative": hottest(stats, CUMULATIVE_TIME, top),
|
||||
"tottime": hottest(stats, TOTAL_TIME, top),
|
||||
}
|
||||
if not roles:
|
||||
raise ansible_log.Unmeasurable(f"no main-*.prof or worker-*.prof in {directory}")
|
||||
return roles
|
||||
|
||||
|
||||
def report(directory: Path | None, top: int) -> tuple[dict, list[str]]:
|
||||
chosen = default_dir() if directory is None else directory
|
||||
roles = merged(chosen, top)
|
||||
lines: list[str] = []
|
||||
for role, found in roles.items():
|
||||
lines.append(f"== {role}: {found['profiles']} profiles, {found['seconds']:.3f} s ==")
|
||||
for order in ("cumulative", "tottime"):
|
||||
lines.append(f"-- {order}: cumtime, tottime, calls, function --")
|
||||
lines += [
|
||||
f"{row['cumtime']:.3f}\t{row['tottime']:.3f}\t{row['calls']}\t{row['function']}" for row in found[order]
|
||||
]
|
||||
return {"dir": str(chosen), **roles}, lines
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Rank timed task occurrences into the reports of durations, gaps, kinds, kind and task.
|
||||
|
||||
Args:
|
||||
source: the source the occurrences came from, echoed in the JSON report.
|
||||
found: the task occurrences of ansible_log.
|
||||
top: rows per table; every row when None.
|
||||
kind: ran, skipped, included or other.
|
||||
needle: substring of the task name.
|
||||
|
||||
Output:
|
||||
A (report, lines) pair: the JSON-ready report and its tab-separated text, biggest
|
||||
first. Name tables end in a TOTAL row over all their tasks; kind tables bucket each
|
||||
occurrence into <0.25, <0.5, <1, <2 or >=2 s.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
import ansible_log
|
||||
|
||||
BUCKETS = ((0.25, "<0.25"), (0.5, "<0.5"), (1.0, "<1"), (2.0, "<2"))
|
||||
LAST_BUCKET = ">=2"
|
||||
LABELS = (*(label for _, label in BUCKETS), LAST_BUCKET)
|
||||
|
||||
Found = list[ansible_log.Task]
|
||||
|
||||
|
||||
def bucket(seconds: float) -> str:
|
||||
return next((label for limit, label in BUCKETS if seconds < limit), LAST_BUCKET)
|
||||
|
||||
|
||||
def ranked(rows: Iterable[dict]) -> list[dict]:
|
||||
return sorted(rows, key=lambda row: -row["sum"])
|
||||
|
||||
|
||||
def of_kind(found: Found, kind: str) -> Found:
|
||||
return [item for item in found if item.kind == kind]
|
||||
|
||||
|
||||
def names(source: str, found: Found, top: int | None) -> tuple[dict, list[str]]:
|
||||
table: dict[str, dict] = {}
|
||||
for item in found:
|
||||
row = table.setdefault(item.name, {"name": item.name, "sum": 0.0, "count": 0})
|
||||
row["sum"] += item.seconds
|
||||
row["count"] += 1
|
||||
rows = ranked(table.values())[:top]
|
||||
total = sum(item.seconds for item in found)
|
||||
report = {
|
||||
"source": source,
|
||||
"rows": [{**row, "sum": round(row["sum"], 3)} for row in rows],
|
||||
"total": {"sum": round(total, 3), "count": len(found)},
|
||||
}
|
||||
lines = [f"{row['sum']:.1f}\t{row['count']}\t{row['name']}" for row in rows]
|
||||
return report, [*lines, f"{total:.1f}\t{len(found)}\tTOTAL"]
|
||||
|
||||
|
||||
def kind_table(source: str, found: Found, top: int | None) -> tuple[dict, list[str]]:
|
||||
table: dict[str, dict] = {}
|
||||
for item in found:
|
||||
row = table.setdefault(
|
||||
item.kind, {"kind": item.kind, "count": 0, "sum": 0.0, "buckets": dict.fromkeys(LABELS, 0)}
|
||||
)
|
||||
row["count"] += 1
|
||||
row["sum"] += item.seconds
|
||||
row["buckets"][bucket(item.seconds)] += 1
|
||||
rows = ranked(table.values())[:top]
|
||||
report = {
|
||||
"source": source,
|
||||
"kinds": [
|
||||
{**row, "sum": round(row["sum"], 3), "mean": round(row["sum"] / row["count"], 4)} for row in rows
|
||||
],
|
||||
}
|
||||
lines = ["\t".join(("kind", "count", "sum", "mean", *LABELS))]
|
||||
lines += [
|
||||
"\t".join(
|
||||
(
|
||||
row["kind"],
|
||||
str(row["count"]),
|
||||
f"{row['sum']:.1f}",
|
||||
f"{row['sum'] / row['count']:.4f}",
|
||||
*(str(row["buckets"][label]) for label in LABELS),
|
||||
)
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
return report, lines
|
||||
|
||||
|
||||
def occurrences(source: str, found: Found, needle: str, top: int | None) -> tuple[dict, list[str]]:
|
||||
hits = sorted((item for item in found if needle in item.name), key=lambda item: -item.seconds)
|
||||
shown = hits[:top]
|
||||
report = {
|
||||
"source": source,
|
||||
"needle": needle,
|
||||
"count": len(hits),
|
||||
"sum": round(sum(item.seconds for item in hits), 3),
|
||||
"occurrences": [
|
||||
{"line": item.line, "seconds": round(item.seconds, 3), "kind": item.kind, "name": item.name}
|
||||
for item in shown
|
||||
],
|
||||
}
|
||||
return report, [f"{item.line}\t{item.seconds:.3f}\t{item.kind}\t{item.name}" for item in shown]
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure where an Ansible run spends its time: from its log, its controller profiles or a bench.
|
||||
|
||||
Subcommands:
|
||||
durations: per task name sum and count of the profile_tasks `(h:mm:ss.sss)` durations.
|
||||
gaps: per task name sum and count of the wall time between the headers of a log
|
||||
whose lines start with an ISO timestamp.
|
||||
kinds: per kind (ran, skipped, included, other) count, sum, mean and the buckets
|
||||
<0.25, <0.5, <1, <2 and >=2 s.
|
||||
kind: per task name sum and count of one --kind.
|
||||
task: every occurrence of the task names holding --needle: start line, seconds, kind.
|
||||
profile-report: the main and worker profiles of --dir merged, by cumulative and own time.
|
||||
bench-carrier: a synthetic JSON fact of exactly --kb KiB written to --out.
|
||||
|
||||
Args:
|
||||
--log: the Ansible output to read.
|
||||
--from, --to: first and last line to read, 1-based and inclusive; the whole log when omitted.
|
||||
--top: rows per table; every row when omitted for a log, required for profile-report.
|
||||
--json: JSON instead of tab-separated text.
|
||||
--source: wall (ISO timestamps) or profile (profile_tasks) for kinds, kind and task;
|
||||
wall when a header in range carries a timestamp, else profile, when omitted.
|
||||
--kind: ran, skipped, included or other.
|
||||
--needle: substring of the task name.
|
||||
--dir: profile directory; $ANSIBLE_PROFILE_DIR, else <TMPDIR>/ansible-profile, when omitted.
|
||||
--kb: size of the synthetic fact in KiB.
|
||||
--out: file the synthetic fact goes to.
|
||||
|
||||
Exit codes:
|
||||
0 success, 2 usage error or nothing measurable in the range.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
# Trip-wire: python3 -I keeps the script directory off sys.path, and the subcommands live there.
|
||||
sys.path.append(str(Path(__file__).resolve().parent))
|
||||
|
||||
import ansible_bench
|
||||
import ansible_log
|
||||
import ansible_profile
|
||||
import ansible_tables
|
||||
|
||||
Report = tuple[dict, list[str]]
|
||||
|
||||
|
||||
def parsed(args: argparse.Namespace, source: str | None) -> tuple[str, ansible_tables.Found]:
|
||||
return ansible_log.tasks(args.log, args.first, args.last, source)
|
||||
|
||||
|
||||
def durations(args: argparse.Namespace) -> Report:
|
||||
return ansible_tables.names(*parsed(args, "profile"), args.top)
|
||||
|
||||
|
||||
def gaps(args: argparse.Namespace) -> Report:
|
||||
return ansible_tables.names(*parsed(args, "wall"), args.top)
|
||||
|
||||
|
||||
def kinds(args: argparse.Namespace) -> Report:
|
||||
return ansible_tables.kind_table(*parsed(args, args.source), args.top)
|
||||
|
||||
|
||||
def kind(args: argparse.Namespace) -> Report:
|
||||
source, found = parsed(args, args.source)
|
||||
return ansible_tables.names(source, ansible_tables.of_kind(found, args.kind), args.top)
|
||||
|
||||
|
||||
def task(args: argparse.Namespace) -> Report:
|
||||
return ansible_tables.occurrences(*parsed(args, args.source), args.needle, args.top)
|
||||
|
||||
|
||||
def profile_report(args: argparse.Namespace) -> Report:
|
||||
return ansible_profile.report(args.dir, args.top)
|
||||
|
||||
|
||||
def bench_carrier(args: argparse.Namespace) -> Report:
|
||||
return ansible_bench.write(args.kb, args.out)
|
||||
|
||||
|
||||
COMMANDS: dict[str, Callable[[argparse.Namespace], Report]] = {
|
||||
"durations": durations,
|
||||
"gaps": gaps,
|
||||
"kinds": kinds,
|
||||
"kind": kind,
|
||||
"task": task,
|
||||
"profile-report": profile_report,
|
||||
"bench-carrier": bench_carrier,
|
||||
}
|
||||
|
||||
|
||||
def positive(text: str) -> int:
|
||||
try:
|
||||
number = int(text)
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError(f"{text!r}: expected a whole number") from None
|
||||
if number < 1:
|
||||
raise argparse.ArgumentTypeError(f"{text!r} is below 1")
|
||||
return number
|
||||
|
||||
|
||||
def parse(argv: list[str]) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
output = argparse.ArgumentParser(add_help=False)
|
||||
output.add_argument("--json", action="store_true")
|
||||
log = argparse.ArgumentParser(add_help=False, parents=[output])
|
||||
log.add_argument("--log", required=True, type=Path)
|
||||
log.add_argument("--from", dest="first", type=positive)
|
||||
log.add_argument("--to", dest="last", type=positive)
|
||||
log.add_argument("--top", type=positive)
|
||||
detect = argparse.ArgumentParser(add_help=False, parents=[log])
|
||||
detect.add_argument("--source", choices=ansible_log.SOURCES)
|
||||
commands.add_parser("durations", parents=[log])
|
||||
commands.add_parser("gaps", parents=[log])
|
||||
commands.add_parser("kinds", parents=[detect])
|
||||
commands.add_parser("kind", parents=[detect]).add_argument("--kind", required=True, choices=ansible_log.KINDS)
|
||||
commands.add_parser("task", parents=[detect]).add_argument("--needle", required=True)
|
||||
report = commands.add_parser("profile-report", parents=[output])
|
||||
report.add_argument("--dir", type=Path)
|
||||
report.add_argument("--top", required=True, type=positive)
|
||||
bench = commands.add_parser("bench-carrier", parents=[output])
|
||||
bench.add_argument("--kb", required=True, type=positive)
|
||||
bench.add_argument("--out", required=True, type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
first, last = getattr(args, "first", None), getattr(args, "last", None)
|
||||
if first is not None and last is not None and first > last:
|
||||
parser.error(f"--from {first} is after --to {last}")
|
||||
return args
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
args = parse(argv)
|
||||
try:
|
||||
report, lines = COMMANDS[args.command](args)
|
||||
except (ansible_log.Unmeasurable, OSError) as error:
|
||||
print(f"ansible_tasks: {error}", file=sys.stderr)
|
||||
return 2
|
||||
print(json.dumps(report, indent=2) if args.json else "\n".join(lines))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Profile ansible-playbook and every worker it forks with cProfile, once on PYTHONPATH.
|
||||
|
||||
Args:
|
||||
ANSIBLE_PROFILE_DIR: directory for main-<pid>.prof and worker-<pid>.prof;
|
||||
<TMPDIR>/ansible-profile when unset.
|
||||
|
||||
Output:
|
||||
Only a process whose argv[0] is named ansible-playbook is profiled. The controller
|
||||
writes its file at exit, each forked worker when it leaves through os._exit.
|
||||
"""
|
||||
|
||||
import atexit
|
||||
import cProfile
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
PROGRAM = "ansible-playbook"
|
||||
|
||||
|
||||
def profile_dir() -> str:
|
||||
# Trip-wire: TMPDIR is the one scratch directory every sandbox lets the run write to.
|
||||
return os.environ.get("ANSIBLE_PROFILE_DIR") or os.path.join(tempfile.gettempdir(), "ansible-profile")
|
||||
|
||||
|
||||
def start(out: str) -> None:
|
||||
os.makedirs(out, exist_ok=True)
|
||||
controller = cProfile.Profile()
|
||||
|
||||
def dump_controller() -> None:
|
||||
controller.disable()
|
||||
controller.dump_stats(os.path.join(out, f"main-{os.getpid()}.prof"))
|
||||
|
||||
def after_fork() -> None:
|
||||
# Trip-wire: the fork inherits the enabled controller profiler; no second one starts beside it.
|
||||
controller.disable()
|
||||
worker = cProfile.Profile()
|
||||
real_exit = os._exit
|
||||
|
||||
def exit_dumping(code: int) -> None:
|
||||
worker.disable()
|
||||
worker.dump_stats(os.path.join(out, f"worker-{os.getpid()}.prof"))
|
||||
real_exit(code)
|
||||
|
||||
# Trip-wire: multiprocessing workers leave through os._exit, which skips atexit.
|
||||
os._exit = exit_dumping
|
||||
worker.enable()
|
||||
|
||||
atexit.register(dump_controller)
|
||||
os.register_at_fork(after_in_child=after_fork)
|
||||
controller.enable()
|
||||
|
||||
|
||||
if os.path.basename(sys.argv[0] if sys.argv else "") == PROGRAM:
|
||||
start(profile_dir())
|
||||
@@ -41,6 +41,7 @@ operator to decide, never applied as a tuning.
|
||||
beats a 60 s download paid once.
|
||||
- **The baseline is the newest log of the current code**; an older one may
|
||||
carry a step since replaced, and a saving against it is fiction.
|
||||
- **Ansible**: measure with the `kvb-check-ansible` skill first.
|
||||
|
||||
## Coordinate every cost cluster
|
||||
|
||||
|
||||
Reference in new issue
Block a user