* сделала, чтобы Postgres был доступен только внутри compose-сети
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
+9
-5
@@ -7,7 +7,7 @@ x-required-roles:
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18.6-alpine
|
||||
container_name: mtusi-postgres
|
||||
container_name: mtuci-postgres
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-messenger}
|
||||
@@ -24,7 +24,7 @@ services:
|
||||
|
||||
redis:
|
||||
image: redis:7.4.1-alpine
|
||||
container_name: mtusi-redis
|
||||
container_name: mtuci-redis
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec", "--save", "60", "1"]
|
||||
ports:
|
||||
- "127.0.0.1:6379:6379"
|
||||
@@ -40,8 +40,8 @@ services:
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtusi-messenger:lab2
|
||||
container_name: mtusi-messenger-lab2
|
||||
image: mtuci-messenger:lab2
|
||||
container_name: mtuci-messenger-lab2
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
env_file:
|
||||
@@ -61,4 +61,8 @@ services:
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
redis-data:
|
||||
redis-data:
|
||||
|
||||
networks:
|
||||
default:
|
||||
name: mtuci2026lab2_default
|
||||
@@ -29,6 +29,10 @@ from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
# Имя compose-сети проекта: <папка-проекта>_default.
|
||||
# Проверить: docker network ls | findstr default
|
||||
COMPOSE_NETWORK = os.environ.get("COMPOSE_NETWORK", "mtusi2026lab2_default")
|
||||
|
||||
|
||||
# ---------- 1. Конкурентная регистрация одинакового username ----------
|
||||
def test_concurrent_registration(c):
|
||||
@@ -67,16 +71,16 @@ def _read_dsn() -> str:
|
||||
dsn = line.split("=", 1)[1].strip()
|
||||
break
|
||||
check(dsn, "DATABASE_URL не найден ни в окружении, ни в .env")
|
||||
# Внутри контейнера хост — host.docker.internal, а не localhost.
|
||||
return dsn.replace("@localhost:", "@host.docker.internal:").replace(
|
||||
"@127.0.0.1:", "@host.docker.internal:")
|
||||
# Postgres доступен только внутри compose-сети; одноразовые psql-контейнеры
|
||||
# запускаются в этой же сети, поэтому имя хоста postgres резолвится как есть.
|
||||
return dsn
|
||||
|
||||
|
||||
def _psql(dsn_in_container: str, sql: str) -> str:
|
||||
r = subprocess.run(
|
||||
[
|
||||
"docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"postgres:18-alpine",
|
||||
"psql", dsn_in_container, "-tA", "-c", sql,
|
||||
],
|
||||
@@ -141,7 +145,7 @@ END $$;
|
||||
r = subprocess.run(
|
||||
[
|
||||
"docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"postgres:18-alpine",
|
||||
"psql", dsn_in_container, "-c", seed_sql,
|
||||
],
|
||||
@@ -173,7 +177,7 @@ END $$;
|
||||
r = subprocess.run(
|
||||
[
|
||||
"docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"postgres:18-alpine",
|
||||
"psql", dsn_in_container, "-c", sql,
|
||||
],
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
5. Границы потери данных: во время pg_dump через API пишем новые сообщения,
|
||||
после restore проверяем, что их нет.
|
||||
|
||||
Все psql-вызовы идут через docker run postgres:18-alpine --add-host=host.docker.internal:host-gateway.
|
||||
Все psql-вызовы идут через docker run postgres:18-alpine в compose-сети проекта
|
||||
(--network <project>_default), DSN указывает на хост postgres.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
@@ -36,6 +37,10 @@ EVIDENCE.mkdir(exist_ok=True)
|
||||
|
||||
SEED_SQL = ROOT / "student-tests" / "track2_seed.sql"
|
||||
|
||||
# Имя compose-сети проекта: <папка-проекта>_default.
|
||||
# Проверить: docker network ls | findstr default
|
||||
COMPOSE_NETWORK = os.environ.get("COMPOSE_NETWORK", "mtusi2026lab2_default")
|
||||
|
||||
|
||||
# ---------- helpers ----------
|
||||
def _read_dsn() -> str:
|
||||
@@ -49,14 +54,15 @@ def _read_dsn() -> str:
|
||||
dsn = line.split("=", 1)[1].strip()
|
||||
break
|
||||
check(dsn, "DATABASE_URL не найден ни в окружении, ни в .env")
|
||||
return dsn.replace("@localhost:", "@host.docker.internal:").replace(
|
||||
"@127.0.0.1:", "@host.docker.internal:")
|
||||
# Postgres доступен только внутри compose-сети; одноразовые psql/pg_dump
|
||||
# контейнеры запускаются в этой же сети, имя хоста postgres резолвится как есть.
|
||||
return dsn
|
||||
|
||||
|
||||
def _psql(dsn: str, sql: str, extra=None):
|
||||
cmd = [
|
||||
"docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"postgres:18-alpine",
|
||||
"psql", dsn, "-tA", "-v", "ON_ERROR_STOP=1",
|
||||
]
|
||||
@@ -69,7 +75,7 @@ def _psql(dsn: str, sql: str, extra=None):
|
||||
def _psql_file(dsn: str, path: Path):
|
||||
cmd = [
|
||||
"docker", "run", "--rm", "-i",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-v", f"{path}:/seed.sql:ro",
|
||||
"postgres:18-alpine",
|
||||
"psql", dsn, "-v", "ON_ERROR_STOP=1", "-f", "/seed.sql",
|
||||
@@ -221,11 +227,11 @@ def step_backup_restore(dsn: str):
|
||||
if out_file.exists():
|
||||
out_file.unlink()
|
||||
|
||||
# pg_dump через docker run (использует образ PG 18)
|
||||
# pg_dump через docker run (использует образ PG 18), в compose-сети
|
||||
t0 = time.monotonic()
|
||||
r = subprocess.run(
|
||||
["docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-v", f"{EVIDENCE}:/out",
|
||||
"postgres:18-alpine",
|
||||
"pg_dump", "-Fc", "-f", "/out/lab2_track2_dump.dump", dsn],
|
||||
@@ -236,14 +242,16 @@ def step_backup_restore(dsn: str):
|
||||
size = out_file.stat().st_size
|
||||
print(" dump size = %.1f MiB, time = %.2fs" % (size / 1024 / 1024, dump_time))
|
||||
|
||||
# новый контейнер как отдельное хранилище
|
||||
# новый контейнер как отдельное хранилище — в той же compose-сети,
|
||||
# порт наружу не публикуем
|
||||
restore_container = "mtusi-pg-restore"
|
||||
subprocess.run(["docker", "rm", "-f", restore_container], capture_output=True)
|
||||
subprocess.run(
|
||||
["docker", "run", "-d", "--name", restore_container,
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-e", "POSTGRES_PASSWORD=restore", "-e", "POSTGRES_USER=postgres",
|
||||
"-e", "POSTGRES_DB=high_load_messenger",
|
||||
"-p", "127.0.0.1:55432:5432", "postgres:18-alpine"],
|
||||
"postgres:18-alpine"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
# ждём готовности
|
||||
@@ -257,16 +265,15 @@ def step_backup_restore(dsn: str):
|
||||
else:
|
||||
raise Failure("restore container не поднялся")
|
||||
|
||||
restore_dsn = "postgresql://postgres:restore@127.0.0.1:55432/high_load_messenger"
|
||||
# pg_restore -c (clean) на пустую БД
|
||||
# pg_restore -c (clean) на пустую БД; restore-контейнер доступен по имени
|
||||
# в compose-сети
|
||||
t0 = time.monotonic()
|
||||
r = subprocess.run(
|
||||
["docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", "host",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-v", f"{EVIDENCE}:/in",
|
||||
"postgres:18-alpine",
|
||||
"pg_restore", "-d", "postgresql://postgres:restore@127.0.0.1:55432/high_load_messenger",
|
||||
"pg_restore", "-d", "postgresql://postgres:restore@mtusi-pg-restore:5432/high_load_messenger",
|
||||
"--no-owner", "--no-privileges", "/in/lab2_track2_dump.dump"],
|
||||
capture_output=True, text=True, timeout=600,
|
||||
)
|
||||
@@ -340,10 +347,10 @@ def step_rpo(dsn: str, base_url: str, ca_file):
|
||||
if out_file.exists():
|
||||
out_file.unlink()
|
||||
|
||||
# pg_dump: тот же приём, что в шаге 4.
|
||||
# pg_dump: тот же приём, что в шаге 4, в compose-сети.
|
||||
proc = subprocess.Popen(
|
||||
["docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-v", f"{EVIDENCE}:/out",
|
||||
"postgres:18-alpine",
|
||||
"pg_dump", "-Fc", "-f", "/out/lab2_track2_rpo.dump", dsn],
|
||||
@@ -365,14 +372,14 @@ def step_rpo(dsn: str, base_url: str, ca_file):
|
||||
code = proc.wait(timeout=300)
|
||||
check(code == 0, "pg_dump для RPO упал")
|
||||
|
||||
# Временный restore-контейнер: публикуем порт 55433 на хост.
|
||||
# Временный restore-контейнер: в compose-сети, без публикации портов.
|
||||
restore_container = "mtusi-pg-rpo"
|
||||
subprocess.run(["docker", "rm", "-f", restore_container], capture_output=True)
|
||||
subprocess.run(
|
||||
["docker", "run", "-d", "--name", restore_container,
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-e", "POSTGRES_PASSWORD=restore", "-e", "POSTGRES_USER=postgres",
|
||||
"-e", "POSTGRES_DB=high_load_messenger",
|
||||
"-p", "127.0.0.1:55433:5432",
|
||||
"postgres:18-alpine"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
@@ -387,14 +394,14 @@ def step_rpo(dsn: str, base_url: str, ca_file):
|
||||
else:
|
||||
raise Failure("restore container для RPO не поднялся")
|
||||
|
||||
# pg_restore идёт в опубликованный порт через host.docker.internal.
|
||||
# pg_restore идёт в restore-контейнер по имени в compose-сети.
|
||||
r = subprocess.run(
|
||||
["docker", "run", "--rm",
|
||||
"--add-host=host.docker.internal:host-gateway",
|
||||
"--network", COMPOSE_NETWORK,
|
||||
"-v", f"{EVIDENCE}:/in",
|
||||
"postgres:18-alpine",
|
||||
"pg_restore", "-d",
|
||||
"postgresql://postgres:restore@host.docker.internal:55433/high_load_messenger",
|
||||
"postgresql://postgres:restore@mtusi-pg-rpo:5432/high_load_messenger",
|
||||
"--no-owner", "--no-privileges", "/in/lab2_track2_rpo.dump"],
|
||||
capture_output=True, text=True, timeout=600,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user