Files
mtusi2026lab3/scripts/bench/lib.sh
T

58 lines
2.4 KiB
Bash

# Shared helpers of the experiment scripts; sourced, not run.
# abspath prints the absolute path of an existing directory in the form the
# Docker CLI accepts for a bind mount (a Windows path under Git Bash).
abspath() {
(cd "$1" && (pwd -W 2>/dev/null || pwd))
}
# meta writes the header of one run: what ran, when, on which commit and
# host. Arguments: file, then key=value pairs added to the record.
meta() {
file=$1
shift
{
printf '{\n'
printf ' "date_utc": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
printf ' "commit": "%s",\n' "$(git rev-parse --short HEAD)"
printf ' "branch": "%s",\n' "$(git branch --show-current)"
printf ' "docker": "%s",\n' "$(docker version --format '{{.Server.Version}}')"
printf ' "host_cpus": "%s",\n' "$(docker info --format '{{.NCPU}}')"
printf ' "host_memory_bytes": "%s",\n' "$(docker info --format '{{.MemTotal}}')"
for pair in "$@"; do
printf ' "%s": "%s",\n' "${pair%%=*}" "${pair#*=}"
done
printf ' "go": "%s"\n' "$(go env GOVERSION 2>/dev/null || echo unknown)"
printf '}\n'
} >"$file"
}
# sample_docker_stats appends the CPU and memory of every container of the
# stand to a JSON-lines file, about every two seconds, until killed.
sample_docker_stats() {
while :; do
docker stats --no-stream --format "{\"t\":$(date +%s),\"name\":\"{{.Name}}\",\"cpu\":\"{{.CPUPerc}}\",\"mem\":\"{{.MemUsage}}\"}" \
$(docker ps -q --filter label=com.docker.compose.project=lab3) 2>/dev/null || true
done >>"$1"
}
# sample_postgres appends, every second, the database's commit counters and
# what its active sessions are waiting for (none: running on CPU).
sample_postgres() {
while :; do
docker compose exec -T postgres psql -U messenger -d messenger -XAtq -c "
SELECT json_build_object(
't', extract(epoch FROM now()),
'xact_commit', xact_commit, 'xact_rollback', xact_rollback,
'tup_inserted', tup_inserted, 'blks_read', blks_read, 'blks_hit', blks_hit,
'active', (SELECT count(*) FROM pg_stat_activity WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid()),
'waits', (SELECT coalesce(json_object_agg(w, n), '{}') FROM (
SELECT coalesce(wait_event_type || ':' || wait_event, 'cpu') AS w, count(*) AS n
FROM pg_stat_activity
WHERE state = 'active' AND backend_type = 'client backend' AND pid <> pg_backend_pid()
GROUP BY 1) AS x))
FROM pg_stat_database WHERE datname = 'messenger'" 2>/dev/null || true
sleep 1
done >>"$1"
}