268 lines
8.4 KiB
Python
Executable file
268 lines
8.4 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
"""
|
|
Deploy-Skript für das Testsystem tippspiel.programmschmiede.de.
|
|
|
|
Lädt das Projekt (tippspiel/public und tippspiel/src) per FTP auf den
|
|
Testsystem-Server hoch und erzeugt dabei eine .htaccess mit den nötigen
|
|
Environment-Variablen (SetEnv) im public/-Verzeichnis.
|
|
|
|
Zugangsdaten werden aus docs/testsystem_credentials.txt gelesen.
|
|
Achtung: Zugangsdaten landen als SetEnv in der .htaccess auf dem Server.
|
|
"""
|
|
|
|
import argparse
|
|
import io
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from ftplib import FTP, error_perm
|
|
|
|
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
CRED_FILE = os.path.join(REPO_ROOT, "docs", "testsystem_credentials.txt")
|
|
APP_DIR = os.path.join(REPO_ROOT, "tippspiel")
|
|
|
|
FTP_HOST = "programmschmiede.de"
|
|
FTP_PORT = 21
|
|
REMOTE_ROOT = "tippspiel.programmschmiede.de"
|
|
|
|
# Konfiguration des Testsystems (falls nicht in den Credentials vorhanden)
|
|
DB_HOST = "localhost"
|
|
DB_USER = "d0489c69"
|
|
APP_URL = "https://tippspiel.programmschmiede.de"
|
|
|
|
# Quelle für den DB-Sync: lokale, bereits migrierte Datenbank (via Docker)
|
|
LOCAL_DB_HOST = "127.0.0.1"
|
|
LOCAL_DB_PORT = "3306"
|
|
LOCAL_DB_USER = "root"
|
|
LOCAL_DB_PASS = "root"
|
|
LOCAL_DB_NAME = "tippspiel2027"
|
|
|
|
# Entfernte DB, in die der Dump eingespielt wird
|
|
REMOTE_DB_HOST = "programmschmiede.de"
|
|
REMOTE_DB_PORT = "3306"
|
|
|
|
|
|
def read_credentials(path):
|
|
creds = {}
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
for line in f:
|
|
line = line.strip()
|
|
if not line or line.startswith("#") or "=" not in line:
|
|
continue
|
|
key, _, value = line.partition("=")
|
|
creds[key.strip()] = value.strip()
|
|
return creds
|
|
|
|
|
|
def build_htaccess(creds):
|
|
return "\n".join(
|
|
[
|
|
"# Auto-generiert von deploy_test.py - NICHT manuell editieren",
|
|
"Options -Indexes",
|
|
"",
|
|
"RewriteEngine On",
|
|
"RewriteCond %{HTTPS} off",
|
|
"RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]",
|
|
"",
|
|
"SetEnv DB_HOST " + DB_HOST,
|
|
"SetEnv DB_USER " + DB_USER,
|
|
"SetEnv DB_PASS " + creds["mysql_pw"],
|
|
"SetEnv DB_NEW_NAME " + creds["mysql_db"],
|
|
"SetEnv APP_URL " + APP_URL,
|
|
"SetEnv IBAN_KEY " + creds.get("iban_key", ""),
|
|
"SetEnv REMINDER_TOKEN " + creds.get("reminder_token", ""),
|
|
"SetEnv APIFOOTBALL_KEY " + creds.get("apifootball_key", ""),
|
|
"",
|
|
]
|
|
)
|
|
|
|
|
|
def run(cmd, env=None, input_data=None):
|
|
"""Führt einen Befehl aus und gibt bei Fehlern eine verständliche Meldung aus."""
|
|
proc = subprocess.run(
|
|
cmd,
|
|
env=env,
|
|
input=input_data,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
if proc.returncode != 0:
|
|
raise RuntimeError(
|
|
"Befehl fehlgeschlagen: %s\n%s" % (" ".join(cmd), proc.stderr.decode("utf-8", "replace"))
|
|
)
|
|
return proc.stdout
|
|
|
|
|
|
def sync_database(creds):
|
|
"""Dumpt die lokale migrierte DB und spielt sie in die entfernte Test-DB ein."""
|
|
remote_db = creds["mysql_db"]
|
|
remote_pw = creds["mysql_pw"]
|
|
|
|
print("== DB-Sync: dumpe lokale '%s' ==" % LOCAL_DB_NAME)
|
|
dump_env = dict(os.environ, MYSQL_PWD=LOCAL_DB_PASS)
|
|
dump = run(
|
|
[
|
|
"mysqldump",
|
|
"-h", LOCAL_DB_HOST, "-P", LOCAL_DB_PORT,
|
|
"-u", LOCAL_DB_USER,
|
|
"--no-tablespaces", "--column-statistics=0",
|
|
"--no-create-db",
|
|
LOCAL_DB_NAME,
|
|
],
|
|
env=dump_env,
|
|
)
|
|
|
|
print("== DB-Sync: leere entfernte '%s' ==" % remote_db)
|
|
remote_env = dict(os.environ, MYSQL_PWD=remote_pw)
|
|
|
|
# Alle vorhandenen Tabellen ermitteln und droppen
|
|
tables_out = run(
|
|
[
|
|
"mysql",
|
|
"-h", REMOTE_DB_HOST, "-P", REMOTE_DB_PORT,
|
|
"-u", DB_USER, remote_db,
|
|
"-N", "-e",
|
|
"SELECT table_name FROM information_schema.tables WHERE table_schema='%s';" % remote_db,
|
|
],
|
|
env=remote_env,
|
|
)
|
|
tables = [t.strip() for t in tables_out.decode("utf-8", "replace").splitlines() if t.strip()]
|
|
if tables:
|
|
drop_sql = "SET FOREIGN_KEY_CHECKS=0; " + " ".join(
|
|
"DROP TABLE IF EXISTS `%s`;" % t for t in tables
|
|
) + " SET FOREIGN_KEY_CHECKS=1;"
|
|
run(
|
|
[
|
|
"mysql",
|
|
"-h", REMOTE_DB_HOST, "-P", REMOTE_DB_PORT,
|
|
"-u", DB_USER, remote_db,
|
|
"-e", drop_sql,
|
|
],
|
|
env=remote_env,
|
|
)
|
|
print(" %d Tabellen gelöscht." % len(tables))
|
|
else:
|
|
print(" keine Tabellen vorhanden.")
|
|
|
|
print("== DB-Sync: spiele Dump in '%s' ein ==" % remote_db)
|
|
with tempfile.NamedTemporaryFile("wb", delete=False, suffix=".sql") as tmp:
|
|
tmp.write(dump)
|
|
dump_path = tmp.name
|
|
try:
|
|
with open(dump_path, "rb") as f:
|
|
run(
|
|
[
|
|
"mysql",
|
|
"-h", REMOTE_DB_HOST, "-P", REMOTE_DB_PORT,
|
|
"-u", DB_USER, remote_db,
|
|
],
|
|
env=remote_env,
|
|
input_data=f.read(),
|
|
)
|
|
finally:
|
|
os.unlink(dump_path)
|
|
|
|
|
|
def mkd_ignore_exists(ftp, name):
|
|
try:
|
|
ftp.mkd(name)
|
|
except error_perm as e:
|
|
if not e.args[0].startswith("550"):
|
|
raise
|
|
|
|
|
|
def upload_dir(ftp, local_dir, remote_dir, skip=None):
|
|
mkd_ignore_exists(ftp, remote_dir)
|
|
skip = skip or set()
|
|
for name in sorted(os.listdir(local_dir)):
|
|
if name in skip:
|
|
print("SKIP", remote_dir + "/" + name)
|
|
continue
|
|
local_path = os.path.join(local_dir, name)
|
|
if os.path.isfile(local_path):
|
|
print("STOR", remote_dir + "/" + name)
|
|
with open(local_path, "rb") as f:
|
|
ftp.storbinary("STOR " + name, f)
|
|
elif os.path.isdir(local_path):
|
|
print("DIR ", remote_dir + "/" + name)
|
|
mkd_ignore_exists(ftp, name)
|
|
ftp.cwd(name)
|
|
upload_dir(ftp, local_path, remote_dir + "/" + name)
|
|
ftp.cwd("..")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Deploy auf das Testsystem tippspiel.programmschmiede.de "
|
|
"(DB-Sync + FTP-Upload von public/ und src/).",
|
|
epilog="Kombinierbar, z.B. --db-only --skip-img-upload für reine DB-Syncs ohne Bilder.",
|
|
)
|
|
parser.add_argument(
|
|
"--skip-db-import",
|
|
action="store_true",
|
|
help="DB-Sync überspringen (keine Daten in die entfernte DB einspielen).",
|
|
)
|
|
parser.add_argument(
|
|
"--db-only",
|
|
action="store_true",
|
|
help="Nur den DB-Sync ausführen, ohne Dateien per FTP hochzuladen.",
|
|
)
|
|
parser.add_argument(
|
|
"--skip-img-upload",
|
|
action="store_true",
|
|
help="public/img/ nicht hochladen (Logos, Flaggen, Icons).",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
if not os.path.isfile(CRED_FILE):
|
|
print("Fehler: Credentials nicht gefunden:", CRED_FILE, file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
creds = read_credentials(CRED_FILE)
|
|
for key in ("ftp_user", "ftp_pw", "mysql_db", "mysql_pw"):
|
|
if key not in creds:
|
|
print("Fehler: Fehlender Eintrag '%s' in %s" % (key, CRED_FILE), file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
htaccess = build_htaccess(creds)
|
|
|
|
if args.skip_db_import:
|
|
print("== DB-Sync übersprungen (--skip-db-import) ==")
|
|
else:
|
|
sync_database(creds)
|
|
|
|
if args.db_only:
|
|
print("\nDB-Sync abgeschlossen (ohne Upload) ->", APP_URL)
|
|
return
|
|
|
|
ftp = FTP()
|
|
ftp.connect(FTP_HOST, FTP_PORT)
|
|
ftp.login(creds["ftp_user"], creds["ftp_pw"])
|
|
|
|
mkd_ignore_exists(ftp, REMOTE_ROOT)
|
|
ftp.cwd(REMOTE_ROOT)
|
|
|
|
for sub in ("public", "src"):
|
|
local_sub = os.path.join(APP_DIR, sub)
|
|
if not os.path.isdir(local_sub):
|
|
print("Fehler: Verzeichnis fehlt:", local_sub, file=sys.stderr)
|
|
sys.exit(1)
|
|
print("== Lade", sub, "hoch ==")
|
|
mkd_ignore_exists(ftp, sub)
|
|
ftp.cwd(sub)
|
|
skip = {"img"} if (sub == "public" and args.skip_img_upload) else None
|
|
upload_dir(ftp, local_sub, REMOTE_ROOT + "/" + sub, skip=skip)
|
|
ftp.cwd("..")
|
|
|
|
print("== Schreibe .htaccess in public/ ==")
|
|
ftp.cwd("public")
|
|
ftp.storbinary("STOR .htaccess", io.BytesIO(htaccess.encode("utf-8")))
|
|
ftp.cwd("..")
|
|
|
|
ftp.quit()
|
|
print("\nDeployment abgeschlossen ->", APP_URL)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|