forked from mtusi2026/mtusi2026lab3
Lab3: fair track-1 database reset, WAL metrics, rolling and clean-clone tooling
This commit is contained in:
+75
-17
@@ -11,6 +11,7 @@ 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
|
||||
@@ -63,6 +64,22 @@ def compose(*args, env_extra=None, check=True):
|
||||
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()
|
||||
|
||||
@@ -132,10 +149,10 @@ def cgroup_all():
|
||||
return result
|
||||
|
||||
|
||||
def psql_json(sql):
|
||||
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', ENV['POSTGRES_DB'], '-c', sql]
|
||||
'-U', ENV['POSTGRES_USER'], '-d', database or ENV['POSTGRES_DB'], '-c', sql]
|
||||
result = run(command)
|
||||
text = result.stdout.strip()
|
||||
if not text:
|
||||
@@ -143,8 +160,8 @@ def psql_json(sql):
|
||||
return json.loads(text.splitlines()[-1])
|
||||
|
||||
|
||||
def db_snapshot():
|
||||
database = psql_json("""
|
||||
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,
|
||||
@@ -153,7 +170,7 @@ def db_snapshot():
|
||||
'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();""")
|
||||
FROM pg_stat_database WHERE datname = current_database();""", database)
|
||||
activity = psql_json("""
|
||||
SELECT json_build_object(
|
||||
'total', count(*),
|
||||
@@ -161,7 +178,7 @@ def db_snapshot():
|
||||
'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();""")
|
||||
FROM pg_stat_activity WHERE datname = current_database();""", database)
|
||||
datasets = psql_json("""
|
||||
SELECT json_build_object(
|
||||
'messages', (SELECT count(*) FROM messages),
|
||||
@@ -169,26 +186,26 @@ def db_snapshot():
|
||||
'users', (SELECT count(*) FROM users),
|
||||
'chats', (SELECT count(*) FROM chats),
|
||||
'db_bytes', pg_database_size(current_database()),
|
||||
'locks', (SELECT count(*) FROM pg_locks));""")
|
||||
'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'));""")
|
||||
'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;""")
|
||||
'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;""")
|
||||
'buffers_backend_fsync', buffers_backend_fsync) FROM pg_stat_bgwriter;""", database)
|
||||
row = activity or {}
|
||||
row['database'] = database or {}
|
||||
row['database'] = db or {}
|
||||
row['datasets'] = datasets or {}
|
||||
row['settings'] = settings or {}
|
||||
row['wal'] = wal or {}
|
||||
@@ -196,7 +213,7 @@ def db_snapshot():
|
||||
return row
|
||||
|
||||
|
||||
def db_activity_sample():
|
||||
def db_activity_sample(database=None):
|
||||
return psql_json("""
|
||||
SELECT json_build_object(
|
||||
'active', count(*) FILTER (WHERE state = 'active'),
|
||||
@@ -207,7 +224,7 @@ def db_activity_sample():
|
||||
FROM pg_stat_activity
|
||||
WHERE state = 'active' AND wait_event_type IS NOT NULL
|
||||
GROUP BY 1) grouped), '{}'::json))
|
||||
FROM pg_stat_activity;""")
|
||||
FROM pg_stat_activity;""", database)
|
||||
|
||||
|
||||
def haproxy_snapshot():
|
||||
@@ -244,12 +261,12 @@ def api_stats():
|
||||
return result
|
||||
|
||||
|
||||
def snapshot():
|
||||
def snapshot(database=None):
|
||||
started = time.monotonic()
|
||||
data = {
|
||||
'collected_at': iso(),
|
||||
'cgroups': cgroup_all(),
|
||||
'db': db_snapshot(),
|
||||
'db': db_snapshot(database),
|
||||
'haproxy': haproxy_snapshot(),
|
||||
'api': api_stats(),
|
||||
'containers': {service: containers(service) for service in SERVICES},
|
||||
@@ -258,6 +275,41 @@ def snapshot():
|
||||
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:
|
||||
@@ -288,8 +340,10 @@ def wait_api_running(expected, timeout=90):
|
||||
|
||||
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):
|
||||
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),
|
||||
@@ -305,7 +359,11 @@ def set_stack_profile(image, revision, replicas, api_cpu, api_mem, gomemlimit,
|
||||
}
|
||||
if recreate_state:
|
||||
compose('up', '-d', '--no-deps', '--force-recreate', 'postgres', 'valkey', 'lb', env_extra=env_extra)
|
||||
compose('up', '-d', '--no-deps', '--force-recreate', 'api', 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')
|
||||
|
||||
Reference in New Issue
Block a user