motorradig2027/tools/backup_motorradig.py

370 lines
13 KiB
Python
Executable file

#!/usr/bin/python3
# Vollständiges Backup für motorradig2027: Datenbank + hochgeladene Dateien.
#
# Gesichert werden standardmäßig:
# - Datenbank-Dump (mysqldump)
# - storage/img_storage (Benutzerbilder, Tourgalerien, PDFs, Mitgliedsanträge)
# - public/img/tour (Tour-Titelbilder)
# - .env (DB-Zugang, VAPID-Schlüssel)
# - storage/dkim (privater DKIM-Schlüssel)
#
# Nicht gesichert werden Code (liegt in Git) und Logs (nur mit --with-logs).
#
# Beispiele:
# python3 tools/backup_motorradig.py
# python3 tools/backup_motorradig.py --output /tmp/opencode
# python3 tools/backup_motorradig.py --skip-media
# python3 tools/backup_motorradig.py --no-secrets --with-logs
#
# Die Zugangsdaten werden aus ../motorradig/.credentials gelesen.
import argparse
import datetime
import ftplib
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
REPO_ROOT = os.path.normpath(os.path.join(TOOLS_DIR, '..'))
APP_ROOT = os.path.join(REPO_ROOT, 'motorradig')
CRED_FILE = os.path.join(APP_ROOT, '.credentials')
REMOTE_BASE = '/motorradig'
# Uploads, die ausschließlich auf dem Server liegen.
MEDIA_TARGETS = [
'storage/img_storage',
'public/img/tour',
]
# Für einen Wiederaufbau benötigte Geheimnisse.
SECRET_TARGETS = [
'.env',
'storage/dkim',
]
LOG_TARGETS = [
'storage/logs',
]
def load_credentials(path: str) -> dict:
creds = {}
if not os.path.isfile(path):
print(f'Fehler: Credentials-Datei nicht gefunden: {path}', file=sys.stderr)
sys.exit(1)
with open(path, 'r', encoding='utf-8') as fh:
for line in fh:
line = line.strip()
if not line or line.startswith('#') or '=' not in line:
continue
key, value = line.split('=', 1)
creds[key.strip()] = value.strip()
return creds
def connect(creds: dict) -> ftplib.FTP_TLS:
ftp = ftplib.FTP_TLS()
ftp.connect(creds['FTP_URL'], 21, timeout=30)
ftp.login(creds['FTP_USER'], creds['FTP_PASSWORD'])
ftp.prot_p()
ftp.set_pasv(True)
ftp.encoding = 'latin-1'
# Binärmodus, damit SIZE und Downloads zuverlässig funktionieren.
ftp.voidcmd('TYPE I')
return ftp
def list_entries(ftp: ftplib.FTP, remote_path: str) -> list:
"""Liefert [(name, typ, größe)] für ein Remote-Verzeichnis."""
try:
entries = []
for name, facts in ftp.mlsd(remote_path):
if name in ('.', '..'):
continue
kind = facts.get('type', 'file')
size = int(facts.get('size', 0) or 0)
entries.append((name, kind, size))
return entries
except ftplib.all_errors:
# Fallback für Server ohne MLSD.
entries = []
for name in ftp.nlst(remote_path):
base = name.rsplit('/', 1)[-1]
if base in ('.', '..'):
continue
full = remote_path.rstrip('/') + '/' + base
try:
size = ftp.size(full)
entries.append((base, 'file', size))
except ftplib.all_errors:
entries.append((base, 'dir', 0))
return entries
def collect_remote(ftp: ftplib.FTP, rel_path: str, out: list) -> None:
"""Sammelt rekursiv (relativer Pfad, typ, größe) unterhalb von rel_path."""
remote_path = REMOTE_BASE + '/' + rel_path
try:
entries = list_entries(ftp, remote_path)
except ftplib.all_errors as exc:
raise RuntimeError(f'{rel_path}: {exc}')
for name, kind, size in sorted(entries, key=lambda item: item[0]):
child = rel_path.rstrip('/') + '/' + name
if kind == 'dir':
out.append((child, 'dir', 0))
collect_remote(ftp, child, out)
elif kind in ('file', 'OS.unix=slink'):
out.append((child, 'file', size))
def remote_file_size(ftp: ftplib.FTP, rel_path: str) -> int:
"""Ermittelt die Dateigröße über MLSD, mit SIZE als Fallback."""
remote = REMOTE_BASE + '/' + rel_path
parent, name = remote.rsplit('/', 1)
try:
for entry, facts in ftp.mlsd(parent):
if entry == name:
return int(facts.get('size', 0) or 0)
except ftplib.all_errors:
pass
try:
return ftp.size(remote)
except ftplib.all_errors:
return 0
def sha256(path: str) -> str:
digest = hashlib.sha256()
with open(path, 'rb') as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b''):
digest.update(chunk)
return digest.hexdigest()
def git_commit() -> str | None:
try:
result = subprocess.run(
['git', '-C', REPO_ROOT, 'rev-parse', 'HEAD'],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
check=True,
text=True,
)
return result.stdout.strip() or None
except (OSError, subprocess.CalledProcessError):
return None
def download(ftp: ftplib.FTP, rel_path: str, size: int, local_root: str) -> dict:
remote = REMOTE_BASE + '/' + rel_path
local = os.path.join(local_root, rel_path.replace('/', os.sep))
os.makedirs(os.path.dirname(local), exist_ok=True)
with open(local, 'wb') as fh:
ftp.retrbinary('RETR ' + remote, fh.write)
os.chmod(local, 0o600)
local_size = os.path.getsize(local)
if size and local_size != size:
raise RuntimeError(f'Größenabweichung: erwartet {size} B, erhalten {local_size} B')
return {
'path': rel_path,
'size': local_size,
'sha256': sha256(local),
}
def main() -> int:
parser = argparse.ArgumentParser(
description='Vollständiges Backup (Datenbank + Uploads) von motorradig2027.',
)
parser.add_argument('--output', default=os.path.join(REPO_ROOT, 'backups'),
help='Zielverzeichnis (Standard: <repo>/backups).')
parser.add_argument('--label', default='', help='Optionaler Namenszusatz für das Backup-Verzeichnis.')
parser.add_argument('--skip-db', action='store_true', help='Datenbank-Dump überspringen.')
parser.add_argument('--skip-media', action='store_true', help='Uploads (img_storage, public/img/tour) überspringen.')
parser.add_argument('--no-secrets', action='store_true', help='.env und DKIM-Schlüssel nicht sichern.')
parser.add_argument('--with-logs', action='store_true', help='storage/logs mit sichern.')
parser.add_argument('--with-credentials', action='store_true', help='Lokale .credentials mit ins Backup kopieren.')
parser.add_argument('--dry-run', action='store_true', help='Nur auflisten, was gesichert würde.')
args = parser.parse_args()
if args.skip_db and args.skip_media and args.no_secrets and not args.with_logs:
print('Fehler: Es würde nichts gesichert werden.', file=sys.stderr)
return 1
creds = load_credentials(CRED_FILE)
stamp = datetime.datetime.now().strftime('%Y-%m-%d_%H%M%S')
label = re.sub(r'[^A-Za-z0-9._-]+', '-', args.label).strip('-')
name = 'motorradig-backup-' + stamp + ('-' + label if label else '')
backup_root = os.path.join(os.path.abspath(args.output), name)
targets = []
if not args.skip_media:
targets.extend(MEDIA_TARGETS)
if not args.no_secrets:
targets.extend(SECRET_TARGETS)
if args.with_logs:
targets.extend(LOG_TARGETS)
if args.dry_run:
print('DRY-RUN: Ziel wäre ' + backup_root)
if not args.skip_db:
print(' DB-Dump')
if not targets:
return 0
ftp = connect(creds)
try:
for rel_path in targets:
remote_path = REMOTE_BASE + '/' + rel_path
if rel_path == '.env':
try:
print(f' Datei {rel_path} ({remote_file_size(ftp, rel_path)} B)')
except ftplib.all_errors as exc:
print(f' FEHLER {rel_path}: {exc}')
else:
try:
count = len(list_entries(ftp, remote_path))
print(f' Verzeichnis {rel_path} ({count} Einträge)')
except ftplib.all_errors as exc:
print(f' FEHLER {rel_path}: {exc}')
finally:
try:
ftp.quit()
except Exception:
ftp.close()
return 0
os.makedirs(backup_root, mode=0o700, exist_ok=True)
os.chmod(backup_root, 0o700)
print('Backup-Verzeichnis: ' + backup_root)
manifest = {
'created_at': datetime.datetime.now().isoformat(timespec='seconds'),
'source_commit': git_commit(),
'remote_base': REMOTE_BASE,
'database_dump': None,
'database_dump_size': None,
'database_dump_sha256': None,
'files': [],
'errors': [],
}
# 1. Datenbank
if not args.skip_db:
try:
from dump_motorradig import dump_database
db_dir = os.path.join(backup_root, 'db')
dump_path = dump_database(db_dir, creds)
os.chmod(db_dir, 0o700)
os.chmod(dump_path, 0o600)
manifest['database_dump'] = os.path.relpath(dump_path, backup_root)
manifest['database_dump_size'] = os.path.getsize(dump_path)
manifest['database_dump_sha256'] = sha256(dump_path)
except Exception as exc:
manifest['errors'].append('DB-Dump: ' + str(exc))
print('FEHLER DB-Dump: ' + str(exc), file=sys.stderr)
# 2. Dateien per FTPS
if targets:
ftp = connect(creds)
try:
remote_files = []
for rel_path in targets:
if rel_path == '.env':
try:
size = remote_file_size(ftp, rel_path)
remote_files.append((rel_path, 'file', size))
except ftplib.all_errors as exc:
manifest['errors'].append(f'{rel_path}: {exc}')
print(f'FEHLER {rel_path}: {exc}', file=sys.stderr)
continue
try:
entries = list_entries(ftp, REMOTE_BASE + '/' + rel_path)
except ftplib.all_errors as exc:
manifest['errors'].append(f'{rel_path}: {exc}')
print(f'FEHLER {rel_path}: {exc}', file=sys.stderr)
continue
del entries
remote_files.append((rel_path, 'dir', 0))
try:
collect_remote(ftp, rel_path, remote_files)
except Exception as exc:
manifest['errors'].append(str(exc))
print(f'FEHLER {exc}', file=sys.stderr)
total = len([item for item in remote_files if item[1] == 'file'])
print(f'{total} Datei(en) werden heruntergeladen …')
index = 0
files_root = os.path.join(backup_root, 'files')
for rel_path, kind, size in remote_files:
local = os.path.join(files_root, rel_path.replace('/', os.sep))
if kind == 'dir':
os.makedirs(local, exist_ok=True)
os.chmod(local, 0o700)
continue
index += 1
print(f'[{index}/{total}] {rel_path}')
try:
manifest['files'].append(download(ftp, rel_path, size, files_root))
except Exception as exc:
message = f'{rel_path}: {exc}'
manifest['errors'].append(message)
print(' FEHLER: ' + str(exc), file=sys.stderr)
if args.with_credentials and os.path.isfile(CRED_FILE):
target = os.path.join(files_root, '.credentials')
os.makedirs(files_root, exist_ok=True)
shutil.copyfile(CRED_FILE, target)
os.chmod(target, 0o600)
manifest['files'].append({
'path': '.credentials',
'size': os.path.getsize(target),
'sha256': sha256(target),
})
print('Lokal kopiert: .credentials')
finally:
try:
ftp.quit()
except Exception:
try:
ftp.close()
except Exception:
pass
# 3. Manifest
manifest['total_bytes'] = sum(item['size'] for item in manifest['files'])
manifest_path = os.path.join(backup_root, 'manifest.json')
with open(manifest_path, 'w', encoding='utf-8') as fh:
json.dump(manifest, fh, indent=2, ensure_ascii=False)
fh.write('\n')
os.chmod(manifest_path, 0o600)
print()
print(f'Dateien: {len(manifest["files"])}, gesamt {manifest["total_bytes"] / 1024 / 1024:.1f} MB')
if manifest['errors']:
print(f'FEHLER: {len(manifest["errors"])} Datei(en) nicht gesichert (siehe manifest.json).', file=sys.stderr)
return 1
print('Fertig.')
return 0
if __name__ == '__main__':
sys.exit(main())