forked from mtusi2026/mtusi2026lab3
565 lines
25 KiB
Python
565 lines
25 KiB
Python
"""Shared measurement helpers for lab3 experiments (Python 3.9+).
|
|
|
|
Metric sources are explicit:
|
|
* loadgen JSON - HTTP acknowledgement throughput and latency;
|
|
* cgroup v2 files - CPU time and throttling of each container (not RSS);
|
|
* PostgreSQL views - commits, tuples, buffer hits, connections, waits;
|
|
* HAProxy CSV - request totals, queues, 5xx and connection errors;
|
|
* internal stats - pgx pool waits and message idempotency counters.
|
|
|
|
Nothing here reads tokens or message bodies. All data is synthetic.
|
|
"""
|
|
import csv
|
|
import datetime as dt
|
|
import re
|
|
import io
|
|
import json
|
|
import os
|
|
import statistics
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
COMPOSE = str(ROOT / 'scripts/compose.sh')
|
|
PROJECT = 'mtusi-lab3-melnikov'
|
|
BASE_URL = 'http://127.0.0.1:8083'
|
|
SERVICES = ('api', 'postgres', 'valkey', 'lb')
|
|
|
|
|
|
def utcnow():
|
|
return dt.datetime.now(dt.timezone.utc)
|
|
|
|
|
|
def iso(value=None):
|
|
return (value or utcnow()).isoformat().replace('+00:00', 'Z')
|
|
|
|
|
|
def read_env():
|
|
values = {}
|
|
for line in (ROOT / '.env').read_text().splitlines():
|
|
line = line.strip()
|
|
if not line or line.startswith('#') or '=' not in line:
|
|
continue
|
|
key, value = line.split('=', 1)
|
|
values[key.strip()] = value.strip()
|
|
return values
|
|
|
|
|
|
ENV = read_env()
|
|
|
|
|
|
def run(command, env=None, check=True, cwd=ROOT, timeout=None):
|
|
result = subprocess.run(command, cwd=str(cwd), env=env, text=True,
|
|
capture_output=True, check=False, timeout=timeout)
|
|
if check and result.returncode != 0:
|
|
raise RuntimeError('command failed (%d): %s\n%s' % (
|
|
result.returncode, ' '.join(command[:6]), (result.stderr or result.stdout)[-800:]))
|
|
return result
|
|
|
|
|
|
def compose(*args, env_extra=None, check=True):
|
|
env = os.environ.copy()
|
|
env.update(env_extra or {})
|
|
return run([COMPOSE, '--env-file', '.env'] + list(args), env=env, check=check)
|
|
|
|
|
|
def remove_service_containers(service):
|
|
"""Remove every container of a compose service, running or stopped.
|
|
|
|
Compose v2 does not reliably converge `deploy.replicas` when a service is
|
|
force-recreated after an earlier scale-down; stale replicas can keep the
|
|
service label and confuse both HAProxy and the experiment. The scaling
|
|
scripts therefore remove the API containers explicitly before creating the
|
|
exact requested count. PostgreSQL/Valkey volumes are never touched here.
|
|
"""
|
|
removed = []
|
|
for item in containers(service, running_only=False):
|
|
run(['docker', 'rm', '-f', item['container_id']], check=False)
|
|
removed.append(item['container_id'])
|
|
return removed
|
|
|
|
|
|
def image_id(container):
|
|
return run(['docker', 'inspect', '-f', '{{.Image}}', container]).stdout.strip()
|
|
|
|
|
|
def containers(service, running_only=True):
|
|
result = run(['docker', 'ps', '-aq',
|
|
'--filter', 'label=com.docker.compose.service=' + service,
|
|
'--filter', 'label=com.docker.compose.project=' + PROJECT])
|
|
items = []
|
|
for container in result.stdout.split():
|
|
data = json.loads(run(['docker', 'inspect', container]).stdout)[0]
|
|
if running_only and data['State']['Status'] != 'running':
|
|
continue
|
|
items.append({
|
|
'container_id': data['Id'],
|
|
'name': data['Name'].lstrip('/'),
|
|
'hostname': data['Config']['Hostname'],
|
|
'image_ref': data['Config']['Image'],
|
|
'image_id': data['Image'],
|
|
'state': data['State']['Status'],
|
|
'started_at': data['State']['StartedAt'],
|
|
'cpu_limit_nano': data['HostConfig'].get('NanoCpus', 0),
|
|
'memory_limit_bytes': data['HostConfig'].get('Memory', 0),
|
|
'cpu_max': read_text(container, '/sys/fs/cgroup/cpu.max').strip(),
|
|
'memory_max': read_text(container, '/sys/fs/cgroup/memory.max').strip(),
|
|
})
|
|
return sorted(items, key=lambda item: item['name'])
|
|
|
|
|
|
def read_text(container, path):
|
|
return run(['docker', 'exec', container, 'cat', path], check=False).stdout
|
|
|
|
|
|
def cgroup(container):
|
|
raw = read_text(container, '/sys/fs/cgroup/cpu.stat')
|
|
values = {}
|
|
for line in raw.splitlines():
|
|
parts = line.split()
|
|
if len(parts) == 2:
|
|
try:
|
|
values[parts[0]] = int(parts[1])
|
|
except ValueError:
|
|
pass
|
|
memory = read_text(container, '/sys/fs/cgroup/memory.current').strip()
|
|
memory_max = read_text(container, '/sys/fs/cgroup/memory.max').strip()
|
|
return {
|
|
'usage_usec': values.get('usage_usec', 0),
|
|
'user_usec': values.get('user_usec', 0),
|
|
'system_usec': values.get('system_usec', 0),
|
|
'nr_periods': values.get('nr_periods', 0),
|
|
'nr_throttled': values.get('nr_throttled', 0),
|
|
'throttled_usec': values.get('throttled_usec', 0),
|
|
'memory_current_bytes': int(memory) if memory.isdigit() else None,
|
|
'memory_max': memory_max,
|
|
}
|
|
|
|
|
|
def cgroup_all():
|
|
result = {}
|
|
for service in SERVICES:
|
|
for item in containers(service):
|
|
result[item['container_id']] = {
|
|
'service': service,
|
|
'hostname': item['hostname'],
|
|
'cgroup': cgroup(item['container_id']),
|
|
}
|
|
return result
|
|
|
|
|
|
def psql_json(sql, database=None):
|
|
command = ['docker', 'exec', '-i', containers('postgres')[0]['container_id'],
|
|
'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
|
|
'-U', ENV['POSTGRES_USER'], '-d', database or ENV['POSTGRES_DB'], '-c', sql]
|
|
result = run(command)
|
|
text = result.stdout.strip()
|
|
if not text:
|
|
return None
|
|
return json.loads(text.splitlines()[-1])
|
|
|
|
|
|
def db_snapshot(database=None):
|
|
db = psql_json("""
|
|
SELECT json_build_object(
|
|
'xact_commit', xact_commit, 'xact_rollback', xact_rollback,
|
|
'blks_read', blks_read, 'blks_hit', blks_hit,
|
|
'tup_returned', tup_returned, 'tup_fetched', tup_fetched,
|
|
'tup_inserted', tup_inserted, 'tup_updated', tup_updated,
|
|
'tup_deleted', tup_deleted, 'deadlocks', deadlocks,
|
|
'temp_files', temp_files, 'temp_bytes', temp_bytes,
|
|
'stats_reset', stats_reset)
|
|
FROM pg_stat_database WHERE datname = current_database();""", database)
|
|
activity = psql_json("""
|
|
SELECT json_build_object(
|
|
'total', count(*),
|
|
'active', count(*) FILTER (WHERE state = 'active'),
|
|
'idle', count(*) FILTER (WHERE state = 'idle'),
|
|
'active_waiting', count(*) FILTER (WHERE state = 'active' AND wait_event_type IS NOT NULL),
|
|
'idle_in_transaction', count(*) FILTER (WHERE state = 'idle in transaction'))
|
|
FROM pg_stat_activity WHERE datname = current_database();""", database)
|
|
datasets = psql_json("""
|
|
SELECT json_build_object(
|
|
'messages', (SELECT count(*) FROM messages),
|
|
'idempotency', (SELECT count(*) FROM message_idempotency),
|
|
'users', (SELECT count(*) FROM users),
|
|
'chats', (SELECT count(*) FROM chats),
|
|
'db_bytes', pg_database_size(current_database()),
|
|
'locks', (SELECT count(*) FROM pg_locks));""", database)
|
|
settings = psql_json("""
|
|
SELECT json_build_object(
|
|
'max_connections', current_setting('max_connections')::int,
|
|
'shared_buffers', current_setting('shared_buffers'),
|
|
'synchronous_commit', current_setting('synchronous_commit'));""", database)
|
|
wal = psql_json("""
|
|
SELECT json_build_object(
|
|
'wal_records', wal_records, 'wal_fpi', wal_fpi, 'wal_bytes', wal_bytes,
|
|
'wal_buffers_full', wal_buffers_full, 'wal_write', wal_write,
|
|
'wal_sync', wal_sync, 'wal_write_time', wal_write_time,
|
|
'wal_sync_time', wal_sync_time) FROM pg_stat_wal;""", database)
|
|
bgwriter = psql_json("""
|
|
SELECT json_build_object(
|
|
'checkpoints_timed', checkpoints_timed, 'checkpoints_req', checkpoints_req,
|
|
'buffers_checkpoint', buffers_checkpoint, 'buffers_clean', buffers_clean,
|
|
'maxwritten_clean', maxwritten_clean, 'buffers_backend', buffers_backend,
|
|
'buffers_backend_fsync', buffers_backend_fsync) FROM pg_stat_bgwriter;""", database)
|
|
row = activity or {}
|
|
row['database'] = db or {}
|
|
row['datasets'] = datasets or {}
|
|
row['settings'] = settings or {}
|
|
row['wal'] = wal or {}
|
|
row['bgwriter'] = bgwriter or {}
|
|
return row
|
|
|
|
|
|
def db_activity_sample(database=None):
|
|
return psql_json("""
|
|
SELECT json_build_object(
|
|
'active', count(*) FILTER (WHERE state = 'active'),
|
|
'waiting', count(*) FILTER (WHERE state = 'active' AND wait_event_type IS NOT NULL),
|
|
'waits', coalesce((
|
|
SELECT json_object_agg(key, n) FROM (
|
|
SELECT wait_event_type || ':' || coalesce(wait_event, '') AS key, count(*) AS n
|
|
FROM pg_stat_activity
|
|
WHERE state = 'active' AND wait_event_type IS NOT NULL
|
|
GROUP BY 1) grouped), '{}'::json))
|
|
FROM pg_stat_activity;""", database)
|
|
|
|
|
|
def haproxy_snapshot():
|
|
container = containers('lb')[0]['container_id']
|
|
result = run(['docker', 'exec', container, 'wget', '-qO-', 'http://127.0.0.1:8404/stats;csv'])
|
|
lines = [line for line in result.stdout.splitlines() if line.strip()]
|
|
if not lines:
|
|
return {}
|
|
header = lines[0].lstrip('# ').split(',')
|
|
rows = {}
|
|
for line in lines[1:]:
|
|
values = next(csv.reader(io.StringIO(line)))
|
|
item = dict(zip(header, values))
|
|
key = item.get('pxname', '') + '/' + item.get('svname', '')
|
|
rows[key] = item
|
|
return {
|
|
'public': rows.get('public/FRONTEND', {}),
|
|
'backend': rows.get('api/BACKEND', {}),
|
|
'servers': {key.split('/', 1)[1]: value for key, value in rows.items()
|
|
if key.startswith('api/') and key not in ('api/BACKEND', 'api/FRONTEND')},
|
|
'collected_at': iso(),
|
|
}
|
|
|
|
|
|
def api_stats():
|
|
result = {}
|
|
for item in containers('api'):
|
|
raw = run(['docker', 'exec', item['container_id'], 'wget', '-qO-',
|
|
'http://127.0.0.1:9090/internal/stats'], check=False).stdout
|
|
try:
|
|
result[item['hostname']] = json.loads(raw)
|
|
except ValueError:
|
|
result[item['hostname']] = {'error': 'stats unavailable'}
|
|
return result
|
|
|
|
|
|
def snapshot(database=None):
|
|
started = time.monotonic()
|
|
data = {
|
|
'collected_at': iso(),
|
|
'cgroups': cgroup_all(),
|
|
'db': db_snapshot(database),
|
|
'haproxy': haproxy_snapshot(),
|
|
'api': api_stats(),
|
|
'containers': {service: containers(service) for service in SERVICES},
|
|
}
|
|
data['collection_seconds'] = round(time.monotonic() - started, 3)
|
|
return data
|
|
|
|
|
|
def admin_psql(sql, database='postgres'):
|
|
container = containers('postgres')[0]['container_id']
|
|
result = run(['docker', 'exec', '-i', container,
|
|
'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
|
|
'-U', ENV['POSTGRES_USER'], '-d', database, '-c', sql], check=False)
|
|
if result.returncode != 0:
|
|
raise RuntimeError('admin psql failed: ' + (result.stderr or result.stdout)[-600:])
|
|
return result.stdout.strip()
|
|
|
|
|
|
def reset_database(name):
|
|
if not re.match(r'^[a-z_][a-z0-9_]*$', name):
|
|
raise ValueError('unsafe database name')
|
|
admin_psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
|
|
"WHERE datname = '%s' AND pid <> pg_backend_pid();" % name)
|
|
admin_psql('DROP DATABASE IF EXISTS "%s";' % name)
|
|
admin_psql('CREATE DATABASE "%s" OWNER "%s";' % (name, ENV['POSTGRES_USER']))
|
|
|
|
|
|
def drop_database(name):
|
|
if not re.match(r'^[a-z_][a-z0-9_]*$', name):
|
|
raise ValueError('unsafe database name')
|
|
admin_psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
|
|
"WHERE datname = '%s' AND pid <> pg_backend_pid();" % name)
|
|
admin_psql('DROP DATABASE IF EXISTS "%s";' % name)
|
|
|
|
|
|
def migrate_database(image, revision, database):
|
|
env_extra = {'API_IMAGE': image, 'GIT_REVISION': revision, 'POSTGRES_DB': database}
|
|
result = compose('run', '--rm', 'migrate', env_extra=env_extra, check=False)
|
|
if result.returncode != 0:
|
|
raise RuntimeError('migrate for %s failed: %s' % (database, (result.stderr or result.stdout)[-800:]))
|
|
return result.stdout.strip().splitlines()[-3:]
|
|
|
|
|
|
def wait_ready(timeout=90):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
result = run(['curl', '-fsS', '-o', '/dev/null', BASE_URL + '/health/ready'], check=False)
|
|
if result.returncode == 0:
|
|
return True
|
|
time.sleep(0.25)
|
|
return False
|
|
|
|
|
|
def wait_api_running(expected, timeout=90):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
items = containers('api')
|
|
if len(items) == expected and all(item['state'] == 'running' for item in items):
|
|
healthy = True
|
|
for item in items:
|
|
status = run(['docker', 'inspect', '-f', '{{if .State.Health}}{{.State.Health.Status}}{{end}}',
|
|
item['container_id']]).stdout.strip()
|
|
if status not in ('healthy',):
|
|
healthy = False
|
|
break
|
|
if healthy:
|
|
return items
|
|
time.sleep(0.25)
|
|
raise RuntimeError('API replicas did not become healthy')
|
|
|
|
|
|
def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit,
|
|
postgres_cpu='0.7', postgres_mem='512M', valkey_cpu='0.1',
|
|
valkey_mem='128M', lb_cpu='0.2', lb_mem='64M', recreate_state=False,
|
|
database='messenger', reset_database_first=False):
|
|
env_extra = {
|
|
'POSTGRES_DB': database,
|
|
'API_IMAGE': image,
|
|
'GIT_REVISION': revision,
|
|
'API_REPLICAS': str(replicas),
|
|
'API_CPU_LIMIT': str(api_cpu),
|
|
'API_MEM_LIMIT': api_mem,
|
|
'GOMEMLIMIT': gomemlimit,
|
|
'POSTGRES_CPU_LIMIT': postgres_cpu,
|
|
'POSTGRES_MEM_LIMIT': postgres_mem,
|
|
'VALKEY_CPU_LIMIT': valkey_cpu,
|
|
'VALKEY_MEM_LIMIT': valkey_mem,
|
|
'LB_CPU_LIMIT': lb_cpu,
|
|
'LB_MEM_LIMIT': lb_mem,
|
|
}
|
|
if recreate_state:
|
|
compose('up', '-d', '--no-deps', '--force-recreate', 'postgres', 'valkey', 'lb', env_extra=env_extra)
|
|
remove_service_containers('api')
|
|
if reset_database_first:
|
|
reset_database(database)
|
|
migrate_database(image, revision, database)
|
|
compose('up', '-d', '--no-deps', 'api', env_extra=env_extra)
|
|
wait_api_running(replicas)
|
|
if not wait_ready(120):
|
|
raise RuntimeError('LB did not become ready')
|
|
return env_extra
|
|
|
|
|
|
def delta(before, after):
|
|
"""Exact deltas for monotonic counters; elapsed is from snapshot times."""
|
|
def cg(snapshot_data):
|
|
return snapshot_data['cgroups']
|
|
result = {'cgroup_api': {}, 'cgroup_postgres': {}, 'cgroup_valkey': {}, 'cgroup_lb': {}}
|
|
for container_id, item in after['cgroups'].items():
|
|
previous = cg(before).get(container_id)
|
|
if not previous:
|
|
continue
|
|
current_values = item['cgroup']
|
|
old_values = previous['cgroup']
|
|
change = {}
|
|
for key in ('usage_usec', 'user_usec', 'system_usec', 'nr_periods', 'nr_throttled', 'throttled_usec'):
|
|
change[key] = current_values.get(key, 0) - old_values.get(key, 0)
|
|
change['memory_current_bytes_end'] = current_values.get('memory_current_bytes')
|
|
change['memory_max'] = current_values.get('memory_max')
|
|
result['cgroup_' + item['service']][container_id] = change
|
|
db_before = before['db']; db_after = after['db']
|
|
result['db'] = {
|
|
'xact_commit': db_after['database']['xact_commit'] - db_before['database']['xact_commit'],
|
|
'xact_rollback': db_after['database']['xact_rollback'] - db_before['database']['xact_rollback'],
|
|
'blks_read': db_after['database']['blks_read'] - db_before['database']['blks_read'],
|
|
'blks_hit': db_after['database']['blks_hit'] - db_before['database']['blks_hit'],
|
|
'tup_inserted': db_after['database']['tup_inserted'] - db_before['database']['tup_inserted'],
|
|
'tup_returned': db_after['database']['tup_returned'] - db_before['database']['tup_returned'],
|
|
'temp_bytes': db_after['database']['temp_bytes'] - db_before['database']['temp_bytes'],
|
|
'deadlocks': db_after['database']['deadlocks'] - db_before['database']['deadlocks'],
|
|
'activity_after': db_after['total'],
|
|
'active_after': db_after['active'],
|
|
'active_waiting_after': db_after['active_waiting'],
|
|
'idle_in_transaction_after': db_after['idle_in_transaction'],
|
|
'settings': db_after['settings'],
|
|
'datasets_after': db_after['datasets'],
|
|
}
|
|
lb_before = before['haproxy']; lb_after = after['haproxy']
|
|
|
|
def number(row, key):
|
|
try:
|
|
return int(float(row.get(key) or 0))
|
|
except ValueError:
|
|
return 0
|
|
result['lb'] = {
|
|
'req_tot_delta': number(lb_after['public'], 'req_tot') - number(lb_before['public'], 'req_tot'),
|
|
'hrsp_5xx_delta': number(lb_after['public'], 'hrsp_5xx') - number(lb_before['public'], 'hrsp_5xx'),
|
|
'hrsp_4xx_delta': number(lb_after['public'], 'hrsp_4xx') - number(lb_before['public'], 'hrsp_4xx'),
|
|
'econ_delta': number(lb_after['backend'], 'econ') - number(lb_before['backend'], 'econ'),
|
|
'eresp_delta': number(lb_after['backend'], 'eresp') - number(lb_before['backend'], 'eresp'),
|
|
'qmax_after': number(lb_after['public'], 'qmax'),
|
|
'qcur_after': number(lb_after['public'], 'qcur'),
|
|
'rtime_ms_after': number(lb_after['backend'], 'rtime'),
|
|
'status_after': lb_after['backend'].get('status'),
|
|
}
|
|
def counter_delta(group, keys):
|
|
change = {}
|
|
for key in keys:
|
|
change[key] = (db_after.get(group, {}).get(key, 0) or 0) - (db_before.get(group, {}).get(key, 0) or 0)
|
|
return change
|
|
result['wal'] = counter_delta('wal', ('wal_records', 'wal_fpi', 'wal_bytes', 'wal_buffers_full',
|
|
'wal_write', 'wal_sync', 'wal_write_time', 'wal_sync_time'))
|
|
result['bgwriter'] = counter_delta('bgwriter', ('checkpoints_timed', 'checkpoints_req',
|
|
'buffers_checkpoint', 'buffers_clean',
|
|
'maxwritten_clean', 'buffers_backend',
|
|
'buffers_backend_fsync'))
|
|
result['api_pool'] = {}
|
|
for instance, current in after['api'].items():
|
|
previous = before['api'].get(instance, {})
|
|
pool_now = current.get('pool', {})
|
|
pool_before = previous.get('pool', {})
|
|
result['api_pool'][instance] = {
|
|
'max_conns': pool_now.get('max_conns'),
|
|
'empty_acquire_delta': pool_now.get('empty_acquire_count', 0) - pool_before.get('empty_acquire_count', 0),
|
|
'canceled_acquire_delta': pool_now.get('canceled_acquire_count', 0) - pool_before.get('canceled_acquire_count', 0),
|
|
'acquire_delta': pool_now.get('acquire_count', 0) - pool_before.get('acquire_count', 0),
|
|
'acquire_ms_delta': pool_now.get('acquire_duration_ms_total', 0) - pool_before.get('acquire_duration_ms_total', 0),
|
|
'total_conns_after': pool_now.get('total_conns'),
|
|
'acquired_conns_after': pool_now.get('acquired_conns'),
|
|
'messages_created_delta': (current.get('messages', {}).get('created', 0) -
|
|
previous.get('messages', {}).get('created', 0)),
|
|
'messages_replayed_delta': (current.get('messages', {}).get('replayed', 0) -
|
|
previous.get('messages', {}).get('replayed', 0)),
|
|
'messages_conflicts_delta': (current.get('messages', {}).get('conflicts', 0) -
|
|
previous.get('messages', {}).get('conflicts', 0)),
|
|
}
|
|
return result
|
|
|
|
|
|
def summarize_run(label, config, before, after, elapsed_seconds, load):
|
|
change = delta(before, after)
|
|
api_cpu = 0.0
|
|
api_throttled = 0.0
|
|
api_limit = 0.0
|
|
for item in after['containers']['api']:
|
|
values = change['cgroup_api'].get(item['container_id'], {})
|
|
api_cpu += values.get('usage_usec', 0) / 1e6
|
|
api_throttled += values.get('throttled_usec', 0) / 1e6
|
|
api_limit += item['cpu_limit_nano'] / 1e9
|
|
postgres_values = next(iter(change['cgroup_postgres'].values()), {})
|
|
valkey_values = next(iter(change['cgroup_valkey'].values()), {})
|
|
lb_values = next(iter(change['cgroup_lb'].values()), {})
|
|
postgres_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['postgres']), 0)
|
|
lb_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['lb']), 0)
|
|
valkey_limit = next((item['cpu_limit_nano'] / 1e9 for item in after['containers']['valkey']), 0)
|
|
total_api_cpu_used = api_cpu / elapsed_seconds
|
|
pool_waits = sum(value.get('empty_acquire_delta', 0) for value in change['api_pool'].values())
|
|
pool_acquires = sum(value.get('acquire_delta', 0) for value in change['api_pool'].values())
|
|
pool_acquire_ms = sum(value.get('acquire_ms_delta', 0) for value in change['api_pool'].values())
|
|
db = change['db']
|
|
lb = change['lb']
|
|
commits = db['xact_commit']
|
|
return {
|
|
'label': label,
|
|
'config': config,
|
|
'measured_seconds': round(elapsed_seconds, 3),
|
|
'loadgen': load,
|
|
'resource': {
|
|
'api_used_cores': round(total_api_cpu_used, 4),
|
|
'api_limit_cores': round(api_limit, 4),
|
|
'api_utilization': round(total_api_cpu_used / api_limit, 4) if api_limit else None,
|
|
'api_throttled_seconds': round(api_throttled, 4),
|
|
'db_used_cores': round(postgres_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
|
|
'db_limit_cores': round(postgres_limit, 4),
|
|
'db_utilization': round(postgres_values.get('usage_usec', 0) / 1e6 / elapsed_seconds / postgres_limit, 4) if postgres_limit else None,
|
|
'db_throttled_seconds': round(postgres_values.get('throttled_usec', 0) / 1e6, 4),
|
|
'db_throttled_periods': postgres_values.get('nr_throttled', 0),
|
|
'valkey_used_cores': round(valkey_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
|
|
'valkey_limit_cores': round(valkey_limit, 4),
|
|
'lb_used_cores': round(lb_values.get('usage_usec', 0) / 1e6 / elapsed_seconds, 4),
|
|
'lb_limit_cores': round(lb_limit, 4),
|
|
'api_cgroup_memory_end_bytes': [value.get('memory_current_bytes_end') for value in change['cgroup_api'].values()],
|
|
'postgres_cgroup_memory_end_bytes': postgres_values.get('memory_current_bytes_end'),
|
|
'valkey_cgroup_memory_end_bytes': valkey_values.get('memory_current_bytes_end'),
|
|
'lb_cgroup_memory_end_bytes': lb_values.get('memory_current_bytes_end'),
|
|
},
|
|
'postgres': {
|
|
'commits_delta': commits,
|
|
'commits_per_second': round(commits / elapsed_seconds, 3),
|
|
'rollbacks_delta': db['xact_rollback'],
|
|
'buffer_hit_ratio': round(db['blks_hit'] / (db['blks_hit'] + db['blks_read']), 6) if (db['blks_hit'] + db['blks_read']) else None,
|
|
'tuples_inserted_delta': db['tup_inserted'],
|
|
'temp_bytes_delta': db['temp_bytes'],
|
|
'deadlocks_delta': db['deadlocks'],
|
|
'connections_after': db['activity_after'],
|
|
'active_after': db['active_after'],
|
|
'active_waiting_after': db['active_waiting_after'],
|
|
'idle_in_transaction_after': db['idle_in_transaction_after'],
|
|
'max_connections': db['settings'].get('max_connections'),
|
|
'datasets_after': db['datasets_after'],
|
|
'pool_waits_delta': pool_waits,
|
|
'pool_acquires_delta': pool_acquires,
|
|
'pool_acquire_ms_delta': pool_acquire_ms,
|
|
'pool_waits_per_acquire': round(pool_waits / pool_acquires, 6) if pool_acquires else 0,
|
|
},
|
|
'lb': lb,
|
|
'wal': change['wal'],
|
|
'bgwriter': change['bgwriter'],
|
|
'snapshot_before_at': before['collected_at'],
|
|
'snapshot_after_at': after['collected_at'],
|
|
}
|
|
|
|
|
|
def median(values):
|
|
values = [value for value in values if value is not None]
|
|
return round(statistics.median(values), 4) if values else None
|
|
|
|
|
|
def run_loadgen(binary, output, duration, warmup, concurrency, note, extra=None):
|
|
command = [str(binary), '-base-url', BASE_URL,
|
|
'-duration', '%ds' % duration, '-warmup', '%ds' % warmup,
|
|
'-concurrency', str(concurrency), '-output', str(output), '-note', note]
|
|
command.extend(extra or [])
|
|
result = run(command, check=False)
|
|
if not Path(output).exists():
|
|
raise RuntimeError('loadgen failed: ' + (result.stderr or result.stdout)[-800:])
|
|
return json.loads(Path(output).read_text())
|
|
|
|
|
|
def build_metadata(image):
|
|
docker_version = run(['docker', 'version', '--format', '{{.Server.Version}}']).stdout.strip()
|
|
info = run(['docker', 'info', '--format', '{{.NCPU}} {{.MemTotal}} {{.OperatingSystem}}']).stdout.strip()
|
|
uname = run(['uname', '-m']).stdout.strip()
|
|
revision = run(['git', 'rev-parse', 'HEAD']).stdout.strip()
|
|
status = run(['git', 'status', '--porcelain']).stdout.strip()
|
|
return {
|
|
'revision': revision,
|
|
'worktree_dirty': bool(status),
|
|
'image': image,
|
|
'docker_server_version': docker_version,
|
|
'docker_vm': info,
|
|
'arch': uname,
|
|
'collected_at': iso(),
|
|
'note': 'One Docker VM (Colima); all API replicas share one kernel, DB and LB. Not independent nodes.',
|
|
}
|