chore: carry lab 3 over

- carry the lab 3 solution over from mtusi2026lab3-safronov
  (solution/bvt2301-safronov, ce89eba): src, migrations, student-tests,
  bench, openspec, .claude, infra/haproxy and infra/valkey, own scripts,
  Dockerfile, compose, pyproject and uv lock
- merge Makefile, .gitignore and .dockerignore (the lab 3 versions only
  add lines to the skeleton, which is the same in lab 4) and
  .env.example (lab 4 skeleton names listed in the header)
- rename the compose project to mtusi-lab4 and the image to :lab4 so
  the stand does not reuse the lab 3 containers and volumes
- update AGENTS.md for lab 4: current lab, origin commit, contract and
  test files of the new skeleton

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-20 17:32:33 +03:00
co-authored by Claude Opus 5.5
parent ec540a1a72
commit 5d5d8f9d2a
365 changed files with 64878 additions and 19 deletions
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env bash
# Сэмплер стенда (решение 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 — статистика недоступна
# Режимы — по второму аргументу:
# 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
roles+=("${arg%%=*}")
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 &
WITH t AS (
SELECT (extract(epoch FROM clock_timestamp()) * 1000)::bigint AS ts
)
SELECT 'act', (SELECT ts FROM t), coalesce(host(client_addr), '-'),
coalesce(state, '-'), coalesce(wait_event_type, 'CPU'),
coalesce(wait_event, '-'), count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend' AND pid <> pg_backend_pid()
GROUP BY 3, 4, 5, 6
UNION ALL
SELECT 'db', (SELECT ts FROM t), xact_commit::text, xact_rollback::text,
sessions::text, sessions_fatal::text, numbackends::bigint
FROM pg_stat_database WHERE datname = current_database()
UNION ALL
SELECT 'wal', (SELECT ts FROM t), wal_records::text, wal_fpi::text,
wal_bytes::text, NULL, NULL
FROM pg_stat_wal
UNION ALL
SELECT 'io', (SELECT ts FROM t), coalesce(sum(writes), 0)::text,
coalesce(sum(fsyncs), 0)::text, NULL, NULL, NULL
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= 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
# каталог может пропасть между проверкой и чтением (контейнер
# остановлен посреди тика): тогда тоже 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
}
vm_line() {
local _cpu user nice system idle iowait irq softirq steal rest total
read -r _cpu user nice system idle iowait irq softirq steal rest </proc/stat
total=$((user + nice + system + idle + iowait + irq + softirq + steal))
read -r _ _ _ _ rest </proc/pressure/cpu
printf 'vm %s %s %s %s\n' "$ns" "$((total - idle - iowait))" "$total" \
"${rest#total=}" >&4
}
lb_lines() {
local line
if ! exec 3<>/dev/tcp/haproxy/8404 2>/dev/null; then
printf 'lb %s missing\n' "$ns" >&4
return
fi
printf 'GET /stats;csv HTTP/1.0\r\n\r\n' >&3
while IFS= read -r line; do
line=${line%$'\r'}
case $line in
"# "* | api,*) printf 'lb %s %s\n' "$ns" "$line" >&4 ;;
esac
done <&3
exec 3<&-
}
hex64='^[0-9a-f]{64}$'
while :; do
# EPOCHREALTIME bash 5 — часы ВМ без запуска date
ns=${EPOCHREALTIME/./}000
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
[[ $mode == list ]] && lb_lines
sleep "$interval"
done