130 lines
4.3 KiB
Python
130 lines
4.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Tear down the IfixKart simulation environment.
|
|
|
|
1. Stop the simulation backend (port 8001, `scripts/sim/run_sim_backend.py`).
|
|
2. Optionally --drop-dbs: drop the three *_sim databases on the remote MySQL.
|
|
|
|
Production services (backend on :8000, the MySQL tunnel) are left running.
|
|
|
|
Usage:
|
|
cd Backend
|
|
./venv/bin/python scripts/sim/teardown.py # stop sim backend only
|
|
./venv/bin/python scripts/sim/teardown.py --drop-dbs # also drop sim DBs
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import os
|
|
import re
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
from dotenv import load_dotenv
|
|
from sqlalchemy import create_engine, text
|
|
|
|
BACKEND_DIR = Path(__file__).resolve().parents[2]
|
|
SIM_ENV = BACKEND_DIR / ".env.sim"
|
|
ARTIFACT_DIR = BACKEND_DIR / "sim-artifacts"
|
|
|
|
SIM_DBS = ["ifixkartecommerce_sim", "ifixkartecommerceadmin_sim", "ifixkartcrm_sim"]
|
|
|
|
|
|
def log(msg: str) -> None:
|
|
print(f"[teardown] {msg}", flush=True)
|
|
|
|
|
|
def stop_sim_backend() -> None:
|
|
result = subprocess.run(
|
|
["pgrep", "-f", "scripts/sim/run_sim_backend.py"],
|
|
capture_output=True, text=True,
|
|
)
|
|
pids = [int(p) for p in result.stdout.split()]
|
|
if not pids:
|
|
log("sim backend: not running")
|
|
return
|
|
for pid in pids:
|
|
try:
|
|
os.kill(pid, signal.SIGTERM)
|
|
log(f"sim backend: sent SIGTERM to pid {pid}")
|
|
except ProcessLookupError:
|
|
pass
|
|
for _ in range(10):
|
|
alive = subprocess.run(["pgrep", "-f", "scripts/sim/run_sim_backend.py"], capture_output=True)
|
|
if alive.returncode != 0:
|
|
break
|
|
time_module_sleep(0.5)
|
|
leftovers = subprocess.run(["pgrep", "-f", "scripts/sim/run_sim_backend.py"], capture_output=True, text=True)
|
|
for pid in [int(p) for p in leftovers.stdout.split()]:
|
|
try:
|
|
os.kill(pid, signal.SIGKILL)
|
|
log(f"sim backend: SIGKILL stubborn pid {pid}")
|
|
except ProcessLookupError:
|
|
pass
|
|
log("sim backend: stopped")
|
|
|
|
|
|
def time_module_sleep(seconds: float) -> None:
|
|
import time
|
|
time.sleep(seconds)
|
|
|
|
|
|
def parse_creds(url: str) -> tuple[str, str, str, str]:
|
|
m = re.match(r"mysql\+pymysql://([^:]+):([^@]+)@([^:/?]+):(\d+)/", url)
|
|
if not m:
|
|
raise SystemExit("Could not parse DB credentials from COMMERCE_DATABASE_URL")
|
|
return m.group(1), m.group(2), m.group(3), m.group(4)
|
|
|
|
|
|
def drop_sim_dbs() -> None:
|
|
if not SIM_ENV.exists():
|
|
raise SystemExit(f"Missing {SIM_ENV}")
|
|
load_dotenv(SIM_ENV, override=True)
|
|
|
|
# Rebuild each sim URL with the same credentials WITHOUT its database name.
|
|
user, password, host, port = parse_creds(os.getenv("COMMERCE_DATABASE_URL", ""))
|
|
base = f"mysql+pymysql://{user}:{password}@{host}:{port}/"
|
|
engine = create_engine(base, future=True)
|
|
with engine.begin() as conn:
|
|
# Safety: only drop databases whose name ends with _sim.
|
|
for db_name in SIM_DBS:
|
|
exists = conn.execute(
|
|
text("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME=:n"),
|
|
{"n": db_name},
|
|
).scalar()
|
|
if not exists:
|
|
log(f"{db_name}: not present, skipped")
|
|
continue
|
|
if not db_name.endswith("_sim"):
|
|
raise SystemExit(f"Refusing to drop non-simulation database {db_name}")
|
|
conn.execute(text(f"DROP DATABASE `{db_name}`"))
|
|
log(f"{db_name}: dropped")
|
|
log("simulation databases dropped")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Stop simulation services and optionally drop sim DBs")
|
|
parser.add_argument("--drop-dbs", action="store_true", help="Also DROP the three *_sim databases")
|
|
args = parser.parse_args()
|
|
|
|
stop_sim_backend()
|
|
if args.drop_dbs:
|
|
drop_sim_dbs()
|
|
else:
|
|
log("databases left intact (pass --drop-dbs to drop them)")
|
|
|
|
stamp = datetime.now(timezone.utc).isoformat()
|
|
(ARTIFACT_DIR / "teardown.json").write_text(
|
|
f'{{"torn_down_at": "{stamp}", "dropped_dbs": {args.drop_dbs}}}\n'
|
|
)
|
|
log("production backend (:8000) and the MySQL tunnel were left untouched")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if sys.platform != "linux":
|
|
raise SystemExit("Linux only")
|
|
raise SystemExit(main())
|