feat: sample CPU and memory in failover and rollout profiles
Run bench/sampler.sh in a new scan mode (cgroup walk, no network, no psql or LB polling) for the whole load of the failover and rollout profiles. bench/resources.py turns the samples into per-window CPU, throttling and memory of every component and the VM, with samples.csv, resources.csv and summary sections; CPU per successful request only in steady windows. Check the peak CPU budget before the stand starts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+29
-6
@@ -16,6 +16,8 @@ from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import resources as res
|
||||
|
||||
# худшее время обнаружения по проверкам LB, с (infra/haproxy/haproxy.cfg:
|
||||
# inter 1s, fastinter 500ms, fall 2, timeout check 2500ms, timeout connect
|
||||
# 500ms): адрес пропал — inter + 0,5 + fastinter + 0,5; зависшая —
|
||||
@@ -474,13 +476,33 @@ def fmt(value: Any) -> str:
|
||||
return str(value)
|
||||
|
||||
|
||||
def limits_line(profile: dict[str, Any]) -> str:
|
||||
"""Строка лимитов шапки сводки; с сэмплером — и его лимит, и k6 без
|
||||
лимита (design change `profile-resources`, решение 7)."""
|
||||
line = (
|
||||
f"- Лимиты без swap: API {profile['cpus']} CPU / "
|
||||
f"{profile['memory']} на реплику, HAProxy {profile['lb_cpus']} CPU / "
|
||||
f"{profile['lb_memory']}, PostgreSQL {profile['db_cpus']} CPU / "
|
||||
f"{profile['db_memory']}, Valkey {profile['cache_cpus']} CPU / "
|
||||
f"{profile['cache_memory']}"
|
||||
)
|
||||
if profile.get("sample_resources"):
|
||||
line += (
|
||||
f", сэмплер {profile['sampler_cpus']} CPU / "
|
||||
f"{profile['sampler_memory']}, k6 без лимита"
|
||||
)
|
||||
return line
|
||||
|
||||
|
||||
def render_summary(
|
||||
meta: dict[str, Any],
|
||||
phases: list[dict[str, Any]],
|
||||
timeline: list[dict[str, Any]],
|
||||
resources: list[dict[str, Any]] | None = None,
|
||||
) -> str:
|
||||
"""`summary.md` профиля отказа: условия, таблица фаз, шкалы вокруг
|
||||
действия и возврата."""
|
||||
действия и возврата; с `resources` (строки `resources.csv`) — ещё
|
||||
ресурсы по фазам и окнам."""
|
||||
profile = meta["profile"]
|
||||
lines = [
|
||||
f"# Отказ реплик под нагрузкой: метка `{meta['label']}`",
|
||||
@@ -498,11 +520,7 @@ def render_summary(
|
||||
f"{profile['failover_down_s']} с до возврата, "
|
||||
f"{profile['failover_after_s']} с после; порог восстановления "
|
||||
f"{profile['failover_success']:.0%}",
|
||||
f"- Лимиты без swap: API {profile['cpus']} CPU / "
|
||||
f"{profile['memory']} на реплику, HAProxy {profile['lb_cpus']} CPU / "
|
||||
f"{profile['lb_memory']}, PostgreSQL {profile['db_cpus']} CPU / "
|
||||
f"{profile['db_memory']}, Valkey {profile['cache_cpus']} CPU / "
|
||||
f"{profile['cache_memory']}",
|
||||
limits_line(profile),
|
||||
"- Посторонние контейнеры в VM во время замера: "
|
||||
+ (", ".join(meta.get("other_containers") or []) or "нет"),
|
||||
"",
|
||||
@@ -538,6 +556,9 @@ def render_summary(
|
||||
f"{fmt(row['pg_idle_tx_terminated'])} | {fmt(row['flags'])} |",
|
||||
)
|
||||
lines.append("")
|
||||
if resources:
|
||||
order = list(dict.fromkeys(r["phase"] for r in resources))
|
||||
lines += res.render_failover(resources, order)
|
||||
for row in phases:
|
||||
rows = [r for r in timeline if r["phase"] == row["phase"]]
|
||||
reach = max(
|
||||
@@ -576,6 +597,8 @@ def render_summary(
|
||||
f"{fmt(r['p95_ms'])} | {fmt(r['instances'])} |",
|
||||
)
|
||||
lines.append("")
|
||||
if resources:
|
||||
lines += res.render_failover_phase(resources, row["phase"])
|
||||
if meta.get("host_warnings"):
|
||||
lines += ["## Предупреждения о хосте", ""]
|
||||
lines += [f"- {w}" for w in meta["host_warnings"]]
|
||||
|
||||
+1102
File diff suppressed because it is too large
Load Diff
+30
-6
@@ -14,6 +14,7 @@ from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import failover
|
||||
import resources as res
|
||||
|
||||
ROLLOUT_FIELDS = [
|
||||
"label",
|
||||
@@ -274,6 +275,29 @@ def start_time(events: list[ContainerEvent]) -> float | None:
|
||||
return create.time if create else None
|
||||
|
||||
|
||||
def script_start(
|
||||
events: list[ContainerEvent],
|
||||
since: float,
|
||||
ignore: frozenset[str] | set[str] = frozenset(),
|
||||
) -> float | None:
|
||||
"""Начало подготовки замены (решение 4 design change
|
||||
`profile-resources`): первое `exec_start` в контейнер проекта не
|
||||
раньше `since` (первого запроса) — первое обращение скрипта к LB.
|
||||
Оркестратор во время нагрузки `docker exec` не делает, k6 — вне
|
||||
проекта; `exec_start` проверок здоровья (`ignore` — их действия)
|
||||
отбрасываются (найдено в apply: они тоже приходят каждые 5 с)."""
|
||||
return next(
|
||||
(
|
||||
e.time
|
||||
for e in events
|
||||
if e.action.startswith("exec_start")
|
||||
and e.action not in ignore
|
||||
and e.time >= since
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def diff(later: Any, earlier: Any) -> float | None:
|
||||
if later is None or earlier is None:
|
||||
return None
|
||||
@@ -515,9 +539,11 @@ def render_summary(
|
||||
row: dict[str, Any] | None,
|
||||
replicas: list[dict[str, Any]],
|
||||
timeline: list[dict[str, Any]],
|
||||
resources: list[dict[str, Any]] | None = None,
|
||||
) -> str:
|
||||
"""`summary.md` профиля замены: условия, итог, шаги по репликам,
|
||||
контейнеры до и после, шкала вокруг замены."""
|
||||
контейнеры до и после, шкала вокруг замены; с `resources` (строки
|
||||
`resources.csv`) — ещё ресурсы по окнам замены."""
|
||||
profile = meta["profile"]
|
||||
info = meta.get("rollout", {})
|
||||
lines = [
|
||||
@@ -537,11 +563,7 @@ def render_summary(
|
||||
f"замены {profile['rollout_budget_s']} с, ещё "
|
||||
f"{profile['rollout_after_s']} с; порог доли успешных "
|
||||
f"{profile['failover_success']:.0%}",
|
||||
f"- Лимиты без swap: API {profile['cpus']} CPU / "
|
||||
f"{profile['memory']} на реплику, HAProxy {profile['lb_cpus']} CPU / "
|
||||
f"{profile['lb_memory']}, PostgreSQL {profile['db_cpus']} CPU / "
|
||||
f"{profile['db_memory']}, Valkey {profile['cache_cpus']} CPU / "
|
||||
f"{profile['cache_memory']}",
|
||||
failover.limits_line(profile),
|
||||
"- Посторонние контейнеры в VM во время замера: "
|
||||
+ (", ".join(meta.get("other_containers") or []) or "нет"),
|
||||
"",
|
||||
@@ -604,6 +626,8 @@ def render_summary(
|
||||
f"{r['errors']} | {r['after_drain']} |",
|
||||
)
|
||||
lines.append("")
|
||||
if resources:
|
||||
lines += res.render_rollout(resources)
|
||||
for title, key in (
|
||||
("до", "containers_before"),
|
||||
("после", "containers_after"),
|
||||
|
||||
+469
-9
@@ -38,6 +38,7 @@ from typing import Any
|
||||
|
||||
import failover
|
||||
import plots
|
||||
import resources
|
||||
import rollout
|
||||
import scaling
|
||||
|
||||
@@ -309,6 +310,11 @@ class Profile:
|
||||
rollout_before_s: int = 0
|
||||
rollout_budget_s: int = 0
|
||||
rollout_after_s: int = 0
|
||||
# профили уровня «4» (failover, rollout): сэмплер в режиме scan на всё
|
||||
# время нагрузки — CPU и память по компонентам и окнам. Признак
|
||||
# наблюдения, нагрузку и окна не меняет; лимиты и интервал сэмплера —
|
||||
# поля sampler_* ниже (design change profile-resources, решение 2)
|
||||
sample_resources: bool = False
|
||||
# серии трека 1 (решения 1–6, 14 design change scaling-bench): имя
|
||||
# серии, конфигурации (реплик, CPU и память реплики, max_connections
|
||||
# PostgreSQL), чаты записи, смесь, фиксированные уровни, лестница и
|
||||
@@ -444,6 +450,7 @@ PROFILES = {
|
||||
failover_before_s=15,
|
||||
failover_down_s=20,
|
||||
failover_after_s=15,
|
||||
sample_resources=True,
|
||||
),
|
||||
"failover_quick": Profile(
|
||||
name="failover_quick",
|
||||
@@ -468,6 +475,7 @@ PROFILES = {
|
||||
failover_before_s=5,
|
||||
failover_down_s=10,
|
||||
failover_after_s=8,
|
||||
sample_resources=True,
|
||||
),
|
||||
# поочерёдная замена под нагрузкой (уровень 4): та же нагрузка и
|
||||
# лимиты, что у failover; реплики стартуют на образе c50b721 —
|
||||
@@ -497,6 +505,7 @@ PROFILES = {
|
||||
rollout_before_s=15,
|
||||
rollout_budget_s=90,
|
||||
rollout_after_s=15,
|
||||
sample_resources=True,
|
||||
),
|
||||
"rollout_quick": Profile(
|
||||
name="rollout_quick",
|
||||
@@ -521,6 +530,7 @@ PROFILES = {
|
||||
rollout_before_s=5,
|
||||
rollout_budget_s=60,
|
||||
rollout_after_s=8,
|
||||
sample_resources=True,
|
||||
),
|
||||
}
|
||||
|
||||
@@ -704,6 +714,51 @@ def budget(profile: Profile, vm_cpus: int, vm_memory: int) -> dict[str, Any]:
|
||||
return result
|
||||
|
||||
|
||||
def level4_budget(
|
||||
profile: Profile,
|
||||
vm_cpus: int,
|
||||
vm_memory: int,
|
||||
) -> dict[str, Any]:
|
||||
"""Сумма лимитов CPU и памяти профиля уровня «4» на пике (решение 8
|
||||
design change `profile-resources`): реплики (у `rollout` — на одну
|
||||
больше: на пике замены работает третья), PostgreSQL, LB, Valkey,
|
||||
сэмплер; генератор — только если у него есть лимит. Миграция идёт до
|
||||
третьей реплики и пик не поднимает."""
|
||||
peak = profile.replicas + (1 if profile.is_rollout else 0)
|
||||
cpu = peak * float(profile.cpus) + sum(
|
||||
float(value)
|
||||
for value in (
|
||||
profile.db_cpus,
|
||||
profile.lb_cpus,
|
||||
profile.cache_cpus,
|
||||
profile.generator_cpus or "0",
|
||||
profile.sampler_cpus,
|
||||
)
|
||||
)
|
||||
mem = peak * size_bytes(profile.memory) + sum(
|
||||
size_bytes(value)
|
||||
for value in (
|
||||
profile.db_memory,
|
||||
profile.lb_memory,
|
||||
profile.cache_memory,
|
||||
profile.generator_memory or "0",
|
||||
profile.sampler_memory,
|
||||
)
|
||||
)
|
||||
return {
|
||||
"cpus": round(cpu, 2),
|
||||
"memory_gib": round(mem / 2**30, 2),
|
||||
"peak_replicas": peak,
|
||||
"vm_cpus": vm_cpus,
|
||||
"vm_memory_gib": round(vm_memory / 2**30, 2),
|
||||
"generator": (
|
||||
f"{profile.generator_cpus} CPU / {profile.generator_memory}"
|
||||
if profile.generator_cpus
|
||||
else "no limit"
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
class BenchError(Exception):
|
||||
"""Стенд не может продолжать: сообщение для человека."""
|
||||
|
||||
@@ -897,11 +952,15 @@ def vm_warnings(profile: Profile) -> list[str]:
|
||||
(k, memory)
|
||||
for k, _, memory, *_ in map(scaling.unpack_config, profile.configs)
|
||||
]
|
||||
extra = (
|
||||
(profile.generator_memory, profile.sampler_memory)
|
||||
if profile.is_series
|
||||
else ()
|
||||
)
|
||||
elif profile.is_rollout and profile.sample_resources:
|
||||
# на пике замены работает третья реплика (design change
|
||||
# profile-resources, решение 8)
|
||||
replicas = [(profile.replicas + 1, profile.memory)]
|
||||
extra: tuple[str, ...] = ()
|
||||
if profile.is_series:
|
||||
extra = (profile.generator_memory, profile.sampler_memory)
|
||||
elif profile.sample_resources:
|
||||
extra = (profile.sampler_memory,)
|
||||
limits = max(k * size_bytes(memory) for k, memory in replicas) + sum(
|
||||
size_bytes(value)
|
||||
for value in (
|
||||
@@ -1299,8 +1358,12 @@ class Stand:
|
||||
"--filter",
|
||||
"type=container",
|
||||
]
|
||||
# exec_start — начало подготовки замены: первое обращение скрипта к
|
||||
# LB (design change profile-resources, решение 4); exec проверок
|
||||
# здоровья контейнеров отсекает rollout.script_start
|
||||
for action in ("create", "start", "kill", "die", "destroy"):
|
||||
args += ["--filter", f"event={action}"]
|
||||
args += ["--filter", "event=exec_start"]
|
||||
args += [
|
||||
"--format",
|
||||
"{{.TimeNano}}|{{.Action}}|{{.Actor.ID}}|"
|
||||
@@ -1574,11 +1637,19 @@ class Stand:
|
||||
)
|
||||
return limits
|
||||
|
||||
def start_sampler(self) -> None:
|
||||
def start_sampler(self, *, scan: bool = False) -> None:
|
||||
"""Сэмплер ячейки серии (решение 7 design change `scaling-bench`):
|
||||
образ PostgreSQL стенда, `--cgroupns host`, свои лимиты; за 5 с
|
||||
должны появиться строки каждого контейнера, ВМ, LB и PostgreSQL.
|
||||
|
||||
`scan` — профили уровня «4» (решения 1, 2 design change
|
||||
`profile-resources`): режим обхода cgroup, контейнер без сети, без
|
||||
метки проекта и без паролей; за 5 с — строки работающих
|
||||
контейнеров проекта, k6, самого сэмплера и ВМ.
|
||||
"""
|
||||
if scan:
|
||||
self.start_scan_sampler()
|
||||
return
|
||||
p = self.profile
|
||||
image = sh("docker", "inspect", "-f", "{{.Config.Image}}", DB)
|
||||
env = dict(
|
||||
@@ -1666,6 +1737,133 @@ class Stand:
|
||||
tail = sh("docker", "logs", "--tail", "5", SAMPLER, check=False)
|
||||
raise BenchError(f"sampler: {problem}\n{tail}")
|
||||
|
||||
def start_scan_sampler(self) -> None:
|
||||
"""Сэмплер в режиме `scan`: `--network none` — к приложению,
|
||||
хранилищам и LB он обратиться не может; без `--label` проекта —
|
||||
иначе `docker compose up` скрипта замены видел бы его сиротой
|
||||
проекта; без `POSTGRES_*` — пароль ему не нужен. `leftovers()` и
|
||||
`stop()` находят его по имени."""
|
||||
p = self.profile
|
||||
image = sh("docker", "inspect", "-f", "{{.Config.Image}}", DB)
|
||||
(self.work_dir / "samples.log").unlink(missing_ok=True)
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"-d",
|
||||
"--name",
|
||||
SAMPLER,
|
||||
"--cgroupns",
|
||||
"host",
|
||||
"--network",
|
||||
"none",
|
||||
"--cpus",
|
||||
p.sampler_cpus,
|
||||
"--memory",
|
||||
p.sampler_memory,
|
||||
"--memory-swap",
|
||||
p.sampler_memory,
|
||||
"-v",
|
||||
f"{SAMPLER_SCRIPT}:/sampler.sh:ro",
|
||||
"-v",
|
||||
f"{self.work_dir}:/work",
|
||||
"--entrypoint",
|
||||
"bash",
|
||||
image,
|
||||
"/sampler.sh",
|
||||
f"{p.sample_interval_s:g}",
|
||||
"scan",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise BenchError(f"sampler did not start: {proc.stderr}")
|
||||
want = {
|
||||
ident[:12]
|
||||
for ident in sh(
|
||||
"docker",
|
||||
"ps",
|
||||
"-q",
|
||||
"--no-trunc",
|
||||
"--filter",
|
||||
f"label=com.docker.compose.project={PROJECT}",
|
||||
).split()
|
||||
}
|
||||
want |= {self.full_id(name)[:12] for name in (K6, SAMPLER)}
|
||||
deadline = time.monotonic() + 5
|
||||
problem = "no samples"
|
||||
while time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
samples = scaling.parse_samples(self.sampler_logs()[0])
|
||||
ids = {ident for _, ident in samples.cg}
|
||||
if want <= ids and samples.vm:
|
||||
return
|
||||
problem = (
|
||||
f"cgroups seen {len(want & ids)}/{len(want)} (missing "
|
||||
f"{sorted(want - ids)}), vm {len(samples.vm)}"
|
||||
)
|
||||
tail = sh("docker", "logs", "--tail", "5", SAMPLER, check=False)
|
||||
raise BenchError(f"sampler: {problem}\n{tail}")
|
||||
|
||||
def container_map(self) -> dict[str, dict[str, str]]:
|
||||
"""id12 → имя и роль контейнера (решение 1 design change
|
||||
`profile-resources`): контейнеры проекта (и удалённые не
|
||||
попадут — их добавляет поток событий) по метке сервиса compose,
|
||||
k6 и сэмплер — по имени."""
|
||||
found: dict[str, dict[str, str]] = {}
|
||||
listing = sh(
|
||||
"docker",
|
||||
"ps",
|
||||
"-a",
|
||||
"--no-trunc",
|
||||
"--filter",
|
||||
f"label=com.docker.compose.project={PROJECT}",
|
||||
"--format",
|
||||
'{{.ID}}|{{.Names}}|{{.Label "com.docker.compose.service"}}',
|
||||
)
|
||||
for line in listing.splitlines():
|
||||
ident, name, service = (line.split("|") + ["", ""])[:3]
|
||||
if ident:
|
||||
found[ident[:12]] = {"name": name, "role": service}
|
||||
for name, role in ((K6, "k6"), (SAMPLER, "sampler")):
|
||||
ident = sh("docker", "inspect", "-f", "{{.Id}}", name, check=False)
|
||||
if re.fullmatch(r"[0-9a-f]{64}", ident):
|
||||
found[ident[:12]] = {"name": name, "role": role}
|
||||
return found
|
||||
|
||||
def healthcheck_actions(self) -> set[str]:
|
||||
"""Действия `exec_start` проверок здоровья контейнеров проекта, как
|
||||
их пишет поток событий: их не путать с обращением скрипта замены к
|
||||
стенду (найдено в apply change `profile-resources`)."""
|
||||
actions = set()
|
||||
names = sh(
|
||||
"docker",
|
||||
"ps",
|
||||
"-q",
|
||||
"--filter",
|
||||
f"label=com.docker.compose.project={PROJECT}",
|
||||
).split()
|
||||
for name in names:
|
||||
test = json.loads(
|
||||
sh(
|
||||
"docker",
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{json .Config.Healthcheck}}",
|
||||
name,
|
||||
check=False,
|
||||
)
|
||||
or "null",
|
||||
)
|
||||
command = (test or {}).get("Test") or []
|
||||
if command[:1] == ["CMD-SHELL"]:
|
||||
actions.add(f"exec_start: /bin/sh -c {' '.join(command[1:])}")
|
||||
elif command[:1] == ["CMD"]:
|
||||
actions.add(f"exec_start: {' '.join(command[1:])}")
|
||||
return actions
|
||||
|
||||
def sampler_logs(self) -> tuple[str, str]:
|
||||
texts = []
|
||||
for name in ("samples.log", "pg-samples.log"):
|
||||
@@ -2540,6 +2738,9 @@ class Results:
|
||||
self.timeline: list[dict[str, Any]] = []
|
||||
self.rollout: dict[str, Any] | None = None
|
||||
self.replaced: list[dict[str, Any]] = []
|
||||
# профили уровня «4»: строки resources.csv для сводки (design
|
||||
# change profile-resources, решение 7)
|
||||
self.resources: list[dict[str, Any]] = []
|
||||
# продолжение серии дописывает в существующий каталог метки
|
||||
(label_dir / "raw").mkdir(parents=True, exist_ok=True)
|
||||
self.write_meta()
|
||||
@@ -2570,6 +2771,27 @@ class Results:
|
||||
{key: row.get(key) for key in scaling.SAMPLE_FIELDS},
|
||||
)
|
||||
|
||||
def add_resources(self, result: resources.Result) -> None:
|
||||
"""Ресурсы фазы или замены: `resources.csv` (по окнам) и
|
||||
`samples.csv` (посекундно) профилей уровня «4»."""
|
||||
self.resources += result.rows
|
||||
for name, fields, rows in (
|
||||
("resources.csv", resources.RESOURCE_FIELDS, result.rows),
|
||||
("samples.csv", resources.SAMPLE_FIELDS, result.samples),
|
||||
):
|
||||
path = self.dir / name
|
||||
new = not path.exists()
|
||||
with path.open("a", newline="", encoding="utf-8") as file:
|
||||
writer = csv.DictWriter(
|
||||
file,
|
||||
fieldnames=fields,
|
||||
lineterminator="\n",
|
||||
)
|
||||
if new:
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
writer.writerow({key: row.get(key) for key in fields})
|
||||
|
||||
def append(
|
||||
self,
|
||||
name: str,
|
||||
@@ -2654,12 +2876,14 @@ class Results:
|
||||
self.rollout,
|
||||
self.replaced,
|
||||
self.timeline,
|
||||
self.resources or None,
|
||||
)
|
||||
elif self.meta["profile"].get("failover_modes"):
|
||||
text = failover.render_summary(
|
||||
self.meta,
|
||||
self.phases,
|
||||
self.timeline,
|
||||
self.resources or None,
|
||||
)
|
||||
else:
|
||||
text = build_summary(
|
||||
@@ -2949,6 +3173,12 @@ class Bench:
|
||||
self.prepared = False
|
||||
# индекс плана приложения: от него варианты и пробы записи
|
||||
self.app_index: str | None = None
|
||||
# ресурсы профилей уровня «4» (design change profile-resources):
|
||||
# контейнеры (id12 → имя и роль сервиса), моменты запуска (id12 →
|
||||
# секунды часов ВМ) и ID вне стенда за весь прогон
|
||||
self.containers: dict[str, dict[str, str]] = {}
|
||||
self.starts: dict[str, list[float]] = {}
|
||||
self.unmapped: set[str] = set()
|
||||
|
||||
# ------------------------------------------------------------ вывод
|
||||
|
||||
@@ -4028,12 +4258,83 @@ class Bench:
|
||||
)
|
||||
return requests, k6_data
|
||||
|
||||
# ------------------------------------- ресурсы профилей уровня «4»
|
||||
|
||||
def start_observer(self, tag: str) -> None:
|
||||
"""Сэмплер в режиме `scan` на всё время нагрузки (решения 1, 2
|
||||
design change `profile-resources`): лимиты сэмплера, прочитанные у
|
||||
контейнера, и карта контейнеров — в паспорт."""
|
||||
p = self.profile
|
||||
stand = self.stand
|
||||
stand.start_sampler(scan=True)
|
||||
meta = self.results.meta
|
||||
meta["limits"]["sampler"] = stand.container_limits(SAMPLER)
|
||||
self.containers.update(stand.container_map())
|
||||
info = meta.setdefault("resources", {})
|
||||
info.update(
|
||||
{
|
||||
"mode": "scan",
|
||||
"interval_s": p.sample_interval_s,
|
||||
"containers": self.containers,
|
||||
"unmapped": 0,
|
||||
},
|
||||
)
|
||||
self.results.write_meta()
|
||||
self.say(
|
||||
f"{tag}: sampler started (scan, {p.sampler_cpus} CPU / "
|
||||
f"{p.sampler_memory}, no network), {len(self.containers)} "
|
||||
"containers",
|
||||
)
|
||||
|
||||
def check_observer(self, name: str, first: float, last: float) -> None:
|
||||
"""Сторож (решение 2): сэмплер работает, и в нагрузке соседние
|
||||
тики ВМ не дальше `GAP_LIMIT_S`. Иначе — отказ с фазой: метка без
|
||||
ресурсов цели не годится."""
|
||||
running = sh(
|
||||
"docker",
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{.State.Running}}",
|
||||
SAMPLER,
|
||||
check=False,
|
||||
)
|
||||
if running != "true":
|
||||
raise BenchError(
|
||||
f"{name}: sampler {SAMPLER} stopped during the load: "
|
||||
"resources not measured",
|
||||
)
|
||||
samples = scaling.parse_samples(self.stand.sampler_logs()[0])
|
||||
gap = resources.max_gap(samples, first, last)
|
||||
if gap > resources.GAP_LIMIT_S:
|
||||
raise BenchError(
|
||||
f"{name}: no sampler ticks for {gap:.1f}s during the load "
|
||||
f"(limit {resources.GAP_LIMIT_S:g}s): resources not measured",
|
||||
)
|
||||
|
||||
def observe(
|
||||
self,
|
||||
result: resources.Result,
|
||||
name: str,
|
||||
profile: str,
|
||||
) -> None:
|
||||
"""Строки ресурсов — в файлы метки, ID вне стенда — в паспорт,
|
||||
строка ресурсов — в терминал."""
|
||||
self.unmapped |= set(result.unmapped)
|
||||
self.results.meta["resources"]["unmapped"] = len(self.unmapped)
|
||||
self.results.add_resources(result)
|
||||
self.results.write_meta()
|
||||
self.say(f"{name}: {resources.terminal_line(result.rows, profile)}")
|
||||
|
||||
def run_failover(self) -> None:
|
||||
"""Профиль отказа реплик (решение 7 design change
|
||||
`graceful-failover`): стенд, читаемый чат и курсоры, затем фазы —
|
||||
каждая реплика в каждом режиме."""
|
||||
каждая реплика в каждом режиме. С `sample_resources` — сэмплер от
|
||||
первой фазы до конца последней (design change
|
||||
`profile-resources`)."""
|
||||
p = self.profile
|
||||
fixture = self.prepare_load("failover")
|
||||
if p.sample_resources:
|
||||
self.start_observer("failover")
|
||||
run_id = secrets.token_hex(4)
|
||||
writes = 0
|
||||
number = 0
|
||||
@@ -4048,6 +4349,8 @@ class Bench:
|
||||
fixture=fixture,
|
||||
writes=writes,
|
||||
)
|
||||
if p.sample_resources:
|
||||
self.stand.stop_sampler()
|
||||
|
||||
def run_phase(
|
||||
self,
|
||||
@@ -4187,6 +4490,15 @@ class Bench:
|
||||
None,
|
||||
)
|
||||
requests, k6_data = self.k6_requests(phase, log_name)
|
||||
if p.sample_resources:
|
||||
self.phase_resources(
|
||||
phase,
|
||||
mode,
|
||||
requests,
|
||||
instance=instance,
|
||||
action=action.time,
|
||||
back=back.time,
|
||||
)
|
||||
summary = parse_summary(self.results.dir / "raw" / f"{phase}-k6.json")
|
||||
timeline = failover.build_timeline(
|
||||
requests,
|
||||
@@ -4277,6 +4589,52 @@ class Bench:
|
||||
)
|
||||
return writes
|
||||
|
||||
def phase_resources(
|
||||
self,
|
||||
phase: str,
|
||||
mode: str,
|
||||
requests: list[failover.Request],
|
||||
*,
|
||||
instance: str,
|
||||
action: float,
|
||||
back: float,
|
||||
) -> None:
|
||||
"""Ресурсы фазы по окнам (решения 4, 5 design change
|
||||
`profile-resources`): разгон — 2 с с первого запроса, до действия,
|
||||
окно отказа до возврата, после возврата до последнего запроса.
|
||||
`docker start` после `stop` / `kill` — новая cgroup, её счёт идёт
|
||||
с момента возврата."""
|
||||
first = min(r.start for r in requests)
|
||||
last = max(r.start for r in requests)
|
||||
self.check_observer(f"phase {phase}", first, last)
|
||||
if mode != "pause":
|
||||
self.starts.setdefault(instance, []).append(back)
|
||||
self.containers.update(self.stand.container_map())
|
||||
roles = {}
|
||||
for ident, item in self.containers.items():
|
||||
role = item["role"]
|
||||
if role == APP_SERVICE:
|
||||
role = "api-target" if ident == instance else "api-other"
|
||||
roles[ident] = role
|
||||
windows = [
|
||||
(resources.WARMUP, first, first + resources.WARMUP_S),
|
||||
("before", first + resources.WARMUP_S, action),
|
||||
("down", action, back),
|
||||
("after", back, last),
|
||||
]
|
||||
result = resources.analyze(
|
||||
scaling.parse_samples(self.stand.sampler_logs()[0]),
|
||||
roles,
|
||||
windows,
|
||||
ref=action,
|
||||
ok_starts=[r.start for r in requests if r.ok],
|
||||
phase=phase,
|
||||
mode=mode,
|
||||
profile="failover",
|
||||
starts=self.starts,
|
||||
)
|
||||
self.observe(result, f"phase {phase}", "failover")
|
||||
|
||||
# ------------------------------------------- профиль поочерёдной замены
|
||||
|
||||
def run_rollout(self) -> None:
|
||||
@@ -4311,6 +4669,9 @@ class Bench:
|
||||
"SELECT version_num FROM alembic_version;\n",
|
||||
)
|
||||
self.results.write_meta()
|
||||
if p.sample_resources:
|
||||
# до потока событий и k6: один create/start сэмплера — до нагрузки
|
||||
self.start_observer("rollout")
|
||||
old = {c["instance"] for c in info["containers_before"]}
|
||||
run_id = secrets.token_hex(4)
|
||||
name = "rollout"
|
||||
@@ -4459,6 +4820,16 @@ class Bench:
|
||||
"missing",
|
||||
)
|
||||
replaced = rollout.replica_rows(steps, containers, slots, requests, t0)
|
||||
if p.sample_resources:
|
||||
self.rollout_resources(
|
||||
requests,
|
||||
containers,
|
||||
t0=t0,
|
||||
end=end_event.time,
|
||||
old=old,
|
||||
new=new,
|
||||
)
|
||||
self.stand.stop_sampler()
|
||||
timeline = rollout.build_timeline(requests, t0, old, new)
|
||||
row = rollout.analyze(
|
||||
requests,
|
||||
@@ -4537,6 +4908,79 @@ class Bench:
|
||||
f"distinct texts, {row['writes']} keys sent",
|
||||
)
|
||||
|
||||
def rollout_resources(
|
||||
self,
|
||||
requests: list[failover.Request],
|
||||
containers: list[rollout.ContainerEvent],
|
||||
*,
|
||||
t0: float,
|
||||
end: float,
|
||||
old: set[str],
|
||||
new: set[str],
|
||||
) -> None:
|
||||
"""Ресурсы замены по окнам (решения 4, 5 design change
|
||||
`profile-resources`): до — от конца разгона до первого обращения
|
||||
скрипта к стенду, подготовка — до создания контейнера миграции,
|
||||
замена — до удаления последней старой реплики, после — до
|
||||
последнего запроса. Роли — по `X-Instance-Id` до и после, по
|
||||
сервису compose и по `create` из потока событий проекта
|
||||
(контейнеры, удалённые до конца прогона)."""
|
||||
first = min(r.start for r in requests)
|
||||
last = max(r.start for r in requests)
|
||||
self.check_observer("rollout", first, last)
|
||||
self.containers.update(self.stand.container_map())
|
||||
for event in containers:
|
||||
ident = event.id[:12]
|
||||
if event.action != "create" or ident in self.containers:
|
||||
continue
|
||||
role = ""
|
||||
if "-migrate-" in event.name:
|
||||
role = "migrate"
|
||||
elif re.search(rf"-{APP_SERVICE}-\d+$", event.name):
|
||||
role = APP_SERVICE
|
||||
self.containers[ident] = {"name": event.name, "role": role}
|
||||
for event in containers:
|
||||
if event.action == "start":
|
||||
self.starts.setdefault(event.id[:12], []).append(event.time)
|
||||
roles = {}
|
||||
for ident, item in self.containers.items():
|
||||
role = item["role"]
|
||||
if ident in old:
|
||||
role = "api-old"
|
||||
elif ident in new:
|
||||
role = "api-new"
|
||||
roles[ident] = role
|
||||
info = self.results.meta["rollout"]
|
||||
prepare = rollout.script_start(
|
||||
containers,
|
||||
first,
|
||||
self.stand.healthcheck_actions(),
|
||||
)
|
||||
info["script_start_at"] = (
|
||||
failover.iso(prepare) if prepare is not None else None
|
||||
)
|
||||
if prepare is None or prepare > t0:
|
||||
prepare = t0
|
||||
windows = [
|
||||
(resources.WARMUP, first, first + resources.WARMUP_S),
|
||||
("before", first + resources.WARMUP_S, prepare),
|
||||
("prepare", prepare, t0),
|
||||
("during", t0, end),
|
||||
("after", end, last),
|
||||
]
|
||||
result = resources.analyze(
|
||||
scaling.parse_samples(self.stand.sampler_logs()[0]),
|
||||
roles,
|
||||
windows,
|
||||
ref=t0,
|
||||
ok_starts=[r.start for r in requests if r.ok],
|
||||
phase="rollout",
|
||||
mode="rollout",
|
||||
profile="rollout",
|
||||
starts=self.starts,
|
||||
)
|
||||
self.observe(result, "rollout", "rollout")
|
||||
|
||||
# ---------------------------------------------- серии трека 1
|
||||
|
||||
def run_series(self) -> None:
|
||||
@@ -5219,8 +5663,8 @@ def main(argv: list[str]) -> int:
|
||||
print(f"bench failed: {exc}", flush=True)
|
||||
return 2
|
||||
plan_budget: dict[str, Any] | None = None
|
||||
if profile.is_series:
|
||||
# сумма лимитов CPU конфигурации не больше CPU ВМ (решение 1)
|
||||
peak_budget: dict[str, Any] | None = None
|
||||
if profile.is_series or profile.sample_resources:
|
||||
info = sh(
|
||||
"docker",
|
||||
"info",
|
||||
@@ -5231,6 +5675,20 @@ def main(argv: list[str]) -> int:
|
||||
vm_cpus, vm_memory = (
|
||||
(int(v) for v in info) if len(info) == 2 else (0, 0)
|
||||
)
|
||||
if profile.sample_resources:
|
||||
# профили уровня «4» с сэмплером: сумма лимитов CPU на пике не
|
||||
# больше CPU ВМ (design change profile-resources, решение 8)
|
||||
peak_budget = level4_budget(profile, vm_cpus, vm_memory)
|
||||
if peak_budget["cpus"] > vm_cpus:
|
||||
print(
|
||||
f"CPU limits at peak ({peak_budget['peak_replicas']} "
|
||||
f"replicas, sampler) {peak_budget['cpus']:g} CPU exceed "
|
||||
f"docker VM CPUs ({vm_cpus})",
|
||||
flush=True,
|
||||
)
|
||||
return 2
|
||||
if profile.is_series:
|
||||
# сумма лимитов CPU конфигурации не больше CPU ВМ (решение 1)
|
||||
plan_budget = budget(profile, vm_cpus, vm_memory)
|
||||
over = [
|
||||
f"{key}: {item['cpus']:g} CPU"
|
||||
@@ -5281,6 +5739,8 @@ def main(argv: list[str]) -> int:
|
||||
}
|
||||
if plan_budget is not None:
|
||||
meta["budget"] = plan_budget
|
||||
if peak_budget is not None:
|
||||
meta["resources"] = {"budget": peak_budget}
|
||||
stand_check = Stand(profile, label_dir)
|
||||
started = time.monotonic()
|
||||
# на macOS монотонные часы во сне стоят, а реальные идут: разница —
|
||||
|
||||
+58
-23
@@ -1,22 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Сэмплер стенда трека 1 (решение 7 design change scaling-bench). Работает
|
||||
# только внутри контейнера mtusi-bench-sampler (образ PostgreSQL стенда,
|
||||
# --cgroupns host, сеть mtusi-bench), не на хосте: его запускает
|
||||
# bench/run.py (Stand.start_sampler). Раз в интервал пишет в
|
||||
# /work/samples.log строки с отметкой часов ВМ в наносекундах:
|
||||
# Сэмплер стенда (решение 7 design change scaling-bench, решение 1 design
|
||||
# change profile-resources). Работает только внутри контейнера
|
||||
# mtusi-bench-sampler (образ PostgreSQL стенда, --cgroupns host), не на
|
||||
# хосте: его запускает bench/run.py (Stand.start_sampler). Раз в интервал
|
||||
# пишет в /work/samples.log строки с отметкой часов ВМ в наносекундах
|
||||
# (одна отметка на весь тик):
|
||||
# cg <нс> <роль> <id12> <usage_usec> <nr_periods> <nr_throttled>
|
||||
# <throttled_usec> <memory.current> <cpu.pressure some total>
|
||||
# cg <нс> <роль> <id12> missing — нет каталога cgroup
|
||||
# vm <нс> <занято jiffies> <всего jiffies> <PSI CPU some total, мкс>
|
||||
# lb <нс> # <заголовок CSV статистики HAProxy> / lb <нс> api,<строка>
|
||||
# lb <нс> missing — статистика недоступна
|
||||
# В фоне psql с \watch пишет /work/pg-samples.log (одно соединение на всю
|
||||
# ячейку): act, db, wal, io — разбор в bench/scaling.py (parse_samples).
|
||||
# Аргументы: <интервал, с> <роль>=<полный id контейнера>…
|
||||
# Режимы — по второму аргументу:
|
||||
# list (серии трека 1): <интервал, с> <роль>=<полный id контейнера>…
|
||||
# Сеть mtusi-bench. Строки cg заданных контейнеров, vm и lb; в фоне
|
||||
# psql с \watch пишет /work/pg-samples.log (одно соединение на всю
|
||||
# ячейку): act, db, wal, io — разбор в bench/scaling.py
|
||||
# (parse_samples).
|
||||
# scan (профили failover и rollout): <интервал, с> scan
|
||||
# Контейнер без сети. На каждом тике — обход /sys/fs/cgroup/docker/*/
|
||||
# (только каталоги с именем из 64 hex — контейнеры), строка
|
||||
# `cg <нс> - <id12> …` на каждый; роли назначает оркестратор. Строки
|
||||
# vm — как в list. Ни psql, ни опроса LB: наблюдатель не обращается к
|
||||
# стенду.
|
||||
set -u
|
||||
|
||||
interval=$1
|
||||
shift
|
||||
mode=list
|
||||
if [[ ${1:-} == scan ]]; then
|
||||
mode=scan
|
||||
shift
|
||||
fi
|
||||
roles=()
|
||||
ids=()
|
||||
for arg in "$@"; do
|
||||
@@ -24,6 +39,7 @@ for arg in "$@"; do
|
||||
ids+=("${arg#*=}")
|
||||
done
|
||||
|
||||
if [[ $mode == list ]]; then
|
||||
export PGPASSWORD="$POSTGRES_PASSWORD"
|
||||
psql "host=postgres user=$POSTGRES_USER dbname=$POSTGRES_DB \
|
||||
application_name=bench-sampler" -XAtq -F '|' >/work/pg-samples.log 2>&1 <<SQL &
|
||||
@@ -50,26 +66,35 @@ SELECT 'io', (SELECT ts FROM t), coalesce(sum(writes), 0)::text,
|
||||
FROM pg_stat_io WHERE object = 'wal'
|
||||
\watch $interval
|
||||
SQL
|
||||
fi
|
||||
|
||||
exec 4>>/work/samples.log
|
||||
|
||||
cg_line() {
|
||||
local role=$1 id=$2 dir=/sys/fs/cgroup/docker/$2
|
||||
local key val usage=0 periods=0 throttled=0 thr_usec=0 mem=0 psi=0 rest
|
||||
local key val usage= periods=0 throttled=0 thr_usec=0 mem= psi=0 rest=
|
||||
if [[ ! -r $dir/cpu.stat ]]; then
|
||||
printf 'cg %s %s %s missing\n' "$ns" "$role" "${id:0:12}" >&4
|
||||
return
|
||||
fi
|
||||
while read -r key val; do
|
||||
case $key in
|
||||
usage_usec) usage=$val ;;
|
||||
nr_periods) periods=$val ;;
|
||||
nr_throttled) throttled=$val ;;
|
||||
throttled_usec) thr_usec=$val ;;
|
||||
esac
|
||||
done <"$dir/cpu.stat"
|
||||
read -r mem <"$dir/memory.current"
|
||||
read -r _ _ _ _ rest <"$dir/cpu.pressure"
|
||||
# каталог может пропасть между проверкой и чтением (контейнер
|
||||
# остановлен посреди тика): тогда тоже missing, а не строка нулей
|
||||
{
|
||||
while read -r key val; do
|
||||
case $key in
|
||||
usage_usec) usage=$val ;;
|
||||
nr_periods) periods=$val ;;
|
||||
nr_throttled) throttled=$val ;;
|
||||
throttled_usec) thr_usec=$val ;;
|
||||
esac
|
||||
done <"$dir/cpu.stat"
|
||||
read -r mem <"$dir/memory.current"
|
||||
read -r _ _ _ _ rest <"$dir/cpu.pressure"
|
||||
} 2>/dev/null
|
||||
if [[ -z $usage || -z $mem ]]; then
|
||||
printf 'cg %s %s %s missing\n' "$ns" "$role" "${id:0:12}" >&4
|
||||
return
|
||||
fi
|
||||
psi=${rest#total=}
|
||||
printf 'cg %s %s %s %s %s %s %s %s %s\n' "$ns" "$role" "${id:0:12}" \
|
||||
"$usage" "$periods" "$throttled" "$thr_usec" "$mem" "$psi" >&4
|
||||
@@ -100,13 +125,23 @@ lb_lines() {
|
||||
exec 3<&-
|
||||
}
|
||||
|
||||
hex64='^[0-9a-f]{64}$'
|
||||
|
||||
while :; do
|
||||
# EPOCHREALTIME bash 5 — часы ВМ без запуска date
|
||||
ns=${EPOCHREALTIME/./}000
|
||||
for i in "${!ids[@]}"; do
|
||||
cg_line "${roles[$i]}" "${ids[$i]}"
|
||||
done
|
||||
if [[ $mode == scan ]]; then
|
||||
for dir in /sys/fs/cgroup/docker/*/; do
|
||||
dir=${dir%/}
|
||||
id=${dir##*/}
|
||||
[[ $id =~ $hex64 ]] && cg_line - "$id"
|
||||
done
|
||||
else
|
||||
for i in "${!ids[@]}"; do
|
||||
cg_line "${roles[$i]}" "${ids[$i]}"
|
||||
done
|
||||
fi
|
||||
vm_line
|
||||
lb_lines
|
||||
[[ $mode == list ]] && lb_lines
|
||||
sleep "$interval"
|
||||
done
|
||||
|
||||
Reference in New Issue
Block a user