- --target programmschmiede (Default) nutzt DB_*, --target netcup nutzt DB_LIVE_* bzw. DB_LIVE_URL; Dateipraefix und Aufraeum-Muster je Ziel - Rechte und Aufbewahrung unveraendert (0600/0700, 14 Dumps) - README: netcup-DB ist nur intern erreichbar (10.35.x.x), Dump muss auf dem Server laufen (SSH oder Cron im Panel)
287 lines
9.5 KiB
Python
Executable file
287 lines
9.5 KiB
Python
Executable file
#!/usr/bin/env python3
|
|
"""
|
|
Dumpt die Remote-DB von Drink it cold nach tools/dumps.
|
|
|
|
Aufruf:
|
|
./dump_drink_it_cold.py # Dump nach tools/dumps, 14 Dumps behalten
|
|
./dump_drink_it_cold.py --keep 30 # 30 Dumps behalten
|
|
./dump_drink_it_cold.py --keep 0 # nichts aufräumen
|
|
./dump_drink_it_cold.py --dir /pfad # anderes Zielverzeichnis
|
|
./dump_drink_it_cold.py --check # nur Verbindung/Parameter prüfen
|
|
./dump_drink_it_cold.py --target netcup # DB der Live-Seite drinkitcold.de
|
|
|
|
Zugangsdaten kommen aus docs/credentials.txt (gitignored):
|
|
--target programmschmiede (Default): DB_HOST, DB_NAME, DB_USER, DB_PASSWORD
|
|
--target netcup: DB_LIVE_HOST (oder DB_LIVE_URL),
|
|
DB_LIVE_NAME, DB_LIVE_USER, DB_LIVE_PASSWORD
|
|
Überschreibbar per Umgebungsvariablen (DB_HOST/DB_PORT/DB_USER/DB_PASS/DB_NAME
|
|
bzw. DB_LIVE_*).
|
|
|
|
Die Dumps enthalten personenbezogene Daten (Namen, Adressen, Telefonnummern,
|
|
E-Mail-Adressen) und werden deshalb mit 0600 in einem 0700-Verzeichnis
|
|
abgelegt. Alte Dumps werden nur nach dem Muster
|
|
drink-it-cold_live_*.sql (programmschmiede) bzw.
|
|
drink-it-cold_netcup_*.sql (netcup) 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", "credentials.txt")
|
|
DEFAULT_DUMP_DIR = os.path.join(REPO_ROOT, "tools", "dumps")
|
|
DEFAULT_KEEP = 14
|
|
|
|
# Ziel-Instanzen: eigenes Dateipräfix, eigene Credential-Keys, eigene
|
|
# Umgebungsvariablen. "programmschmiede" bleibt der Default, damit bestehende
|
|
# Aufrufe und Cronjobs unverändert weiterlaufen.
|
|
TARGETS = {
|
|
"programmschmiede": {
|
|
"file_prefix": "live",
|
|
"creds": {"host": "DB_HOST", "name": "DB_NAME", "user": "DB_USER",
|
|
"password": "DB_PASSWORD", "port": "DB_PORT"},
|
|
"env": {"host": "DB_HOST", "port": "DB_PORT", "user": "DB_USER",
|
|
"password": "DB_PASS", "name": "DB_NAME"},
|
|
"url_key": None,
|
|
},
|
|
"netcup": {
|
|
"file_prefix": "netcup",
|
|
"creds": {"host": "DB_LIVE_HOST", "name": "DB_LIVE_NAME", "user": "DB_LIVE_USER",
|
|
"password": "DB_LIVE_PASSWORD", "port": "DB_LIVE_PORT"},
|
|
"env": {"host": "DB_LIVE_HOST", "port": "DB_LIVE_PORT", "user": "DB_LIVE_USER",
|
|
"password": "DB_LIVE_PASSWORD", "name": "DB_LIVE_NAME"},
|
|
"url_key": "DB_LIVE_URL",
|
|
},
|
|
}
|
|
|
|
|
|
def dump_pattern(target):
|
|
return "drink-it-cold_%s_*.sql" % TARGETS[target]["file_prefix"]
|
|
|
|
|
|
def log(message=""):
|
|
print(message, flush=True)
|
|
|
|
|
|
def read_credentials(path):
|
|
"""Liest KEY: value (credentials.txt) und KEY=value (ältere Dateien)."""
|
|
creds = {}
|
|
with open(path, "r", encoding="utf-8") as handle:
|
|
for line in handle:
|
|
line = line.strip()
|
|
if not line or line.startswith("#"):
|
|
continue
|
|
if "=" in line and (":" not in line or line.index("=") < line.index(":")):
|
|
key, _, value = line.partition("=")
|
|
elif ":" in line:
|
|
key, _, value = line.partition(":")
|
|
else:
|
|
continue
|
|
creds[key.strip()] = value.strip()
|
|
return creds
|
|
|
|
|
|
def connection(target):
|
|
if not os.path.isfile(CRED_FILE):
|
|
raise SystemExit("Fehler: Credentials nicht gefunden: %s" % CRED_FILE)
|
|
|
|
spec = TARGETS[target]
|
|
creds = read_credentials(CRED_FILE)
|
|
|
|
def value(field):
|
|
"""Erst Umgebungsvariable, dann credentials.txt."""
|
|
return os.environ.get(spec["env"][field]) or creds.get(spec["creds"][field]) or ""
|
|
|
|
host = value("host")
|
|
port = value("port")
|
|
|
|
# netcup hinterlegt die Verbindung als DB_LIVE_URL ("host:port" bzw. DSN).
|
|
if spec["url_key"]:
|
|
raw = os.environ.get(spec["url_key"]) or creds.get(spec["url_key"]) or ""
|
|
if raw:
|
|
raw = raw.split("://")[-1]
|
|
raw = raw.split("@")[-1].split("/")[0]
|
|
url_host, _, url_port = raw.partition(":")
|
|
host = host or url_host
|
|
port = port or url_port
|
|
|
|
conn = {
|
|
"target": target,
|
|
"host": host,
|
|
"port": port or "3306",
|
|
"user": value("user"),
|
|
"password": value("password"),
|
|
"name": value("name"),
|
|
}
|
|
|
|
missing = [field for field in ("host", "user", "password", "name") if not conn[field]]
|
|
if missing:
|
|
raise SystemExit(
|
|
"Fehler: Fehlende Angaben in %s für --target %s: %s"
|
|
% (CRED_FILE, target, ", ".join(spec["creds"][field] for field in missing))
|
|
)
|
|
return conn
|
|
|
|
|
|
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)
|
|
with open(path, "rb") as handle:
|
|
handle.seek(max(0, os.path.getsize(path) - 200))
|
|
if b"Dump completed" not in handle.read():
|
|
raise SystemExit("Fehler: Dump wirkt unvollständig (Abschlusszeile fehlt): %s" % path)
|
|
os.chmod(path, 0o600)
|
|
return path
|
|
|
|
|
|
def prune(dump_dir, keep, pattern):
|
|
if keep <= 0:
|
|
return []
|
|
dumps = sorted(glob.glob(os.path.join(dump_dir, 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 Remote-DB nach tools/dumps und räumt alte Dumps auf.",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog="Beispiele:\n"
|
|
" %(prog)s\n"
|
|
" %(prog)s --target netcup\n"
|
|
" %(prog)s --keep 30\n"
|
|
" %(prog)s --keep 0\n"
|
|
" %(prog)s --check\n",
|
|
)
|
|
parser.add_argument("--target", choices=sorted(TARGETS), default="programmschmiede",
|
|
help="Datenbank-Instanz (Default: %(default)s)")
|
|
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(args.target)
|
|
pattern = dump_pattern(args.target)
|
|
log("Ziel: %s@%s:%s/%s (%s)" % (conn["user"], conn["host"], conn["port"], conn["name"], args.target))
|
|
|
|
check_connection(conn)
|
|
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, "drink-it-cold_%s_%s.sql" % (TARGETS[args.target]["file_prefix"], stamp)
|
|
)
|
|
|
|
fd, tmp_path = tempfile.mkstemp(prefix=".drink-it-cold_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, pattern)
|
|
for path in removed:
|
|
log("Alte Datei gelöscht: %s" % path)
|
|
remaining = sorted(glob.glob(os.path.join(args.dir, 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)
|