220 lines
6.8 KiB
Python
Executable file
220 lines
6.8 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
"""
|
|
Dumpt die Live-DB des Tippspiels nach tools/dumps.
|
|
|
|
Aufruf:
|
|
./dump_tippspiel.py # Dump nach tools/dumps, 14 Dumps behalten
|
|
./dump_tippspiel.py --keep 30 # 30 Dumps behalten
|
|
./dump_tippspiel.py --keep 0 # nichts aufräumen
|
|
./dump_tippspiel.py --dir /pfad # anderes Zielverzeichnis
|
|
./dump_tippspiel.py --check # nur Verbindung/Parameter prüfen
|
|
|
|
Zugangsdaten kommen aus docs/live_credentials.txt (gitignored), überschreibbar
|
|
per Umgebungsvariablen DB_HOST / DB_PORT / DB_USER / DB_PASS / DB_NAME.
|
|
|
|
Die Dumps enthalten personenbezogene Daten (E-Mails, PayPal-Adressen,
|
|
IBAN-Ciphertexte) und werden deshalb mit 0600 in einem 0700-Verzeichnis
|
|
abgelegt. Alte Dumps werden nur nach dem Muster tippspiel_live_*.sql gelöscht.
|
|
"""
|
|
|
|
import argparse
|
|
import glob
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from datetime import datetime
|
|
|
|
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
CRED_FILE = os.path.join(REPO_ROOT, "docs", "live_credentials.txt")
|
|
DEFAULT_DUMP_DIR = os.path.join(REPO_ROOT, "tools", "dumps")
|
|
DUMP_PATTERN = "tippspiel_live_*.sql"
|
|
DEFAULT_KEEP = 14
|
|
|
|
|
|
def log(message=""):
|
|
print(message, flush=True)
|
|
|
|
|
|
def read_credentials(path):
|
|
creds = {}
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
for line in handle:
|
|
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 connection():
|
|
if not os.path.isfile(CRED_FILE):
|
|
raise SystemExit("Fehler: Credentials nicht gefunden: %s" % CRED_FILE)
|
|
|
|
creds = read_credentials(CRED_FILE)
|
|
missing = [key for key in ("ftp_url", "mysql_db", "mysql_pw") if not creds.get(key)]
|
|
if missing:
|
|
raise SystemExit(
|
|
"Fehler: Fehlende Einträge in %s: %s" % (CRED_FILE, ", ".join(missing))
|
|
)
|
|
|
|
return {
|
|
"host": os.environ.get("DB_HOST") or creds.get("db_host") or creds["ftp_url"],
|
|
"port": os.environ.get("DB_PORT") or creds.get("db_port") or "3306",
|
|
"user": os.environ.get("DB_USER") or creds.get("mysql_user") or creds["mysql_db"],
|
|
"password": os.environ.get("DB_PASS") or creds["mysql_pw"],
|
|
"name": os.environ.get("DB_NAME") or creds["mysql_db"],
|
|
}
|
|
|
|
|
|
def dump_command(conn):
|
|
return [
|
|
"mysqldump",
|
|
"--no-tablespaces",
|
|
"--column-statistics=0",
|
|
"--single-transaction",
|
|
"--quick",
|
|
"--default-character-set=utf8mb4",
|
|
"-h", str(conn["host"]),
|
|
"-P", str(conn["port"]),
|
|
"-u", str(conn["user"]),
|
|
str(conn["name"]),
|
|
]
|
|
|
|
|
|
def ensure_private_dir(path):
|
|
os.makedirs(path, mode=0o700, exist_ok=True)
|
|
try:
|
|
os.chmod(path, 0o700)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def check_connection(conn):
|
|
env = dict(os.environ, MYSQL_PWD=str(conn["password"]))
|
|
proc = subprocess.run(
|
|
[
|
|
"mysql",
|
|
"--connect-timeout=15",
|
|
"--default-character-set=utf8mb4",
|
|
"-h", str(conn["host"]),
|
|
"-P", str(conn["port"]),
|
|
"-u", str(conn["user"]),
|
|
"-N", "-B", "-e", "SELECT 1;",
|
|
str(conn["name"]),
|
|
],
|
|
env=env,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
if proc.returncode != 0:
|
|
raise SystemExit(
|
|
"Fehler: Datenbank nicht erreichbar:\n%s"
|
|
% proc.stderr.decode("utf-8", "replace").strip()
|
|
)
|
|
|
|
|
|
def dump_database(conn, path):
|
|
env = dict(os.environ, MYSQL_PWD=str(conn["password"]))
|
|
with open(path, "wb") as out:
|
|
proc = subprocess.run(
|
|
dump_command(conn),
|
|
env=env,
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=out,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
if proc.returncode != 0:
|
|
raise SystemExit(
|
|
"Fehler: mysqldump fehlgeschlagen:\n%s"
|
|
% proc.stderr.decode("utf-8", "replace").strip()
|
|
)
|
|
if os.path.getsize(path) == 0:
|
|
raise SystemExit("Fehler: Dump ist leer: %s" % path)
|
|
os.chmod(path, 0o600)
|
|
return path
|
|
|
|
|
|
def prune(dump_dir, keep):
|
|
if keep <= 0:
|
|
return []
|
|
dumps = sorted(glob.glob(os.path.join(dump_dir, DUMP_PATTERN)))
|
|
removed = []
|
|
for path in dumps[:-keep]:
|
|
try:
|
|
os.unlink(path)
|
|
removed.append(path)
|
|
except OSError as exc:
|
|
log(" Warnung: konnte %s nicht löschen: %s" % (path, exc))
|
|
return removed
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Dumpt die Live-DB nach tools/dumps und räumt alte Dumps auf.",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog="Beispiele:\n"
|
|
" %(prog)s\n"
|
|
" %(prog)s --keep 30\n"
|
|
" %(prog)s --keep 0\n"
|
|
" %(prog)s --check\n",
|
|
)
|
|
parser.add_argument("--dir", default=os.environ.get("DUMP_DIR", DEFAULT_DUMP_DIR),
|
|
help="Zielverzeichnis (Default: %(default)s)")
|
|
parser.add_argument("--keep", type=int, default=DEFAULT_KEEP,
|
|
help="Anzahl aufzubewahrender Dumps, 0 = nichts löschen "
|
|
"(Default: %(default)s)")
|
|
parser.add_argument("--check", action="store_true",
|
|
help="nur Verbindung und Parameter prüfen, keinen Dump schreiben")
|
|
args = parser.parse_args()
|
|
|
|
if args.keep < 0:
|
|
parser.error("--keep darf nicht negativ sein")
|
|
|
|
conn = connection()
|
|
log("Ziel: %s@%s:%s/%s" % (conn["user"], conn["host"], conn["port"], conn["name"]))
|
|
|
|
try:
|
|
check_connection(conn)
|
|
except SystemExit:
|
|
raise
|
|
log("Login: OK")
|
|
|
|
if args.check:
|
|
log("Check beendet, kein Dump geschrieben.")
|
|
return 0
|
|
|
|
ensure_private_dir(args.dir)
|
|
stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
|
|
final_path = os.path.join(args.dir, "tippspiel_live_%s.sql" % stamp)
|
|
|
|
fd, tmp_path = tempfile.mkstemp(prefix=".tippspiel_dump_", suffix=".tmp", dir=args.dir)
|
|
os.close(fd)
|
|
try:
|
|
dump_database(conn, tmp_path)
|
|
os.replace(tmp_path, final_path)
|
|
finally:
|
|
if os.path.exists(tmp_path):
|
|
os.unlink(tmp_path)
|
|
|
|
size_mb = os.path.getsize(final_path) / 1024 / 1024
|
|
log("Dump: %s (%.1f MB, 0600)" % (final_path, size_mb))
|
|
|
|
removed = prune(args.dir, args.keep)
|
|
for path in removed:
|
|
log("Alte Datei gelöscht: %s" % path)
|
|
remaining = sorted(glob.glob(os.path.join(args.dir, DUMP_PATTERN)))
|
|
log("Vorhanden: %d Dump(s)%s" % (
|
|
len(remaining),
|
|
"" if args.keep <= 0 else " (keep=%d)" % args.keep,
|
|
))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
sys.exit(main())
|
|
except KeyboardInterrupt:
|
|
sys.exit(130)
|