254 lines
8.0 KiB
Python
254 lines
8.0 KiB
Python
"""Datenbank-Backup, Wiederherstellung und Konfigurationsexport.
|
|
|
|
Die Backup-Datei ist eine vollständige SQLite-Datenbank. Sie wird über die
|
|
SQLite-Backup-API erzeugt und kann deshalb auch bei aktivem WAL-Modus
|
|
konsistent heruntergeladen werden. Beim Hochladen wird die Datei vor dem
|
|
Ersetzen der Live-Datenbank auf Integrität und die wichtigsten Tabellen
|
|
geprüft.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sqlite3
|
|
import tempfile
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
from flask import (
|
|
Blueprint,
|
|
Response,
|
|
abort,
|
|
after_this_request,
|
|
current_app,
|
|
flash,
|
|
redirect,
|
|
request,
|
|
send_file,
|
|
url_for,
|
|
)
|
|
|
|
from cmbnet.auth import role_required
|
|
from cmbnet.db import get_db
|
|
from cmbnet.db.database import ensure_schema
|
|
from cmbnet.services.groups_service import GroupsService
|
|
from cmbnet.utils.helpers import notify_reload
|
|
|
|
admin_backup_bp = Blueprint('admin_backup', __name__)
|
|
|
|
# Mindestens diese Tabellen muss ein gültiges CMBNet-Backup enthalten. Ältere
|
|
# Backups werden nach der Wiederherstellung durch ``ensure_schema`` ergänzt.
|
|
REQUIRED_TABLES = frozenset({'tenants', 'accounts', 'groups', 'streets'})
|
|
|
|
# Werte dieser Schlüssel werden in der Konfigurationsanzeige und im Export
|
|
# maskiert. Der Administrator sieht alle Schlüssel, aber keine Geheimnisse,
|
|
# mit denen sich Sessions oder FCM-Zugänge übernehmen lassen.
|
|
SECRET_CONFIG_KEYS = frozenset({
|
|
'SECRET_KEY',
|
|
'FCM_SERVICE_ACCOUNT_JSON',
|
|
})
|
|
|
|
|
|
def _format_config_value(value):
|
|
if isinstance(value, bool):
|
|
return 'true' if value else 'false'
|
|
if value is None:
|
|
return ''
|
|
if isinstance(value, (dict, list, tuple, set)):
|
|
return json.dumps(value, ensure_ascii=False, default=str, sort_keys=True)
|
|
return str(value)
|
|
|
|
|
|
def _is_secret_config_key(key):
|
|
upper = str(key).upper()
|
|
return upper in SECRET_CONFIG_KEYS or 'PASSWORD' in upper
|
|
|
|
|
|
def collect_config_items():
|
|
"""Liefert alle Konfigurationswerte als sortierte ``(Key, Value)``-Liste.
|
|
|
|
Geheimnisse werden maskiert, damit ein versehentlich weitergegebener
|
|
Export keine Session- oder Service-Account-Schlüssel enthält. Der
|
|
Schlüssel selbst bleibt sichtbar, sodass die Liste vollständig ist.
|
|
"""
|
|
items = []
|
|
for key in sorted(current_app.config):
|
|
if _is_secret_config_key(key):
|
|
value = '*** maskiert ***'
|
|
else:
|
|
value = _format_config_value(current_app.config[key])
|
|
items.append((key, value))
|
|
return items
|
|
|
|
|
|
@admin_backup_bp.route('/backup/download')
|
|
@role_required('Administrator')
|
|
def download_backup(**kwargs):
|
|
"""Erzeugt einen konsistenten SQLite-Snapshot und liefert ihn als Datei."""
|
|
source = get_db()
|
|
source.commit()
|
|
|
|
temp = tempfile.NamedTemporaryFile(
|
|
prefix='cmbnet-backup-',
|
|
suffix='.sqlite3',
|
|
delete=False,
|
|
)
|
|
temp_path = Path(temp.name)
|
|
temp.close()
|
|
|
|
destination = None
|
|
try:
|
|
destination = sqlite3.connect(str(temp_path))
|
|
source.backup(destination)
|
|
destination.commit()
|
|
except Exception:
|
|
current_app.logger.exception('Datenbank-Backup konnte nicht erstellt werden.')
|
|
try:
|
|
destination.close()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
temp_path.unlink()
|
|
except OSError:
|
|
pass
|
|
abort(500, 'Backup konnte nicht erstellt werden.')
|
|
|
|
try:
|
|
destination.close()
|
|
except Exception:
|
|
pass
|
|
|
|
@after_this_request
|
|
def remove_temp_file(response):
|
|
try:
|
|
temp_path.unlink()
|
|
except OSError:
|
|
pass
|
|
return response
|
|
|
|
filename = f'cmbnet-backup-{datetime.now():%Y%m%d-%H%M%S}.sqlite3'
|
|
return send_file(
|
|
temp_path,
|
|
mimetype='application/vnd.sqlite3',
|
|
as_attachment=True,
|
|
download_name=filename,
|
|
max_age=0,
|
|
)
|
|
|
|
|
|
def _validate_backup_file(path):
|
|
"""Prüft Integrität und Grundschema einer hochgeladenen SQLite-Datei."""
|
|
conn = sqlite3.connect(str(path))
|
|
try:
|
|
result = conn.execute('PRAGMA integrity_check').fetchone()
|
|
if not result or str(result[0]).lower() != 'ok':
|
|
raise ValueError('Die Datei ist keine gültige SQLite-Datenbank.')
|
|
|
|
tables = {
|
|
str(row[0])
|
|
for row in conn.execute(
|
|
"SELECT name FROM sqlite_master WHERE type = 'table'"
|
|
).fetchall()
|
|
}
|
|
missing = REQUIRED_TABLES - tables
|
|
if missing:
|
|
raise ValueError(
|
|
'Das Backup ist unvollständig. Fehlende Tabellen: '
|
|
+ ', '.join(sorted(missing))
|
|
)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
@admin_backup_bp.route('/backup/restore', methods=['POST'])
|
|
@role_required('Administrator')
|
|
def restore_backup(**kwargs):
|
|
"""Ersetzt die Live-Datenbank durch ein hochgeladenes Backup."""
|
|
upload = request.files.get('backup')
|
|
if upload is None or not upload.filename:
|
|
flash('Bitte eine Backup-Datei auswählen.', 'error')
|
|
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
|
|
|
|
max_bytes = int(current_app.config.get(
|
|
'BACKUP_MAX_UPLOAD_BYTES', 256 * 1024 * 1024
|
|
))
|
|
if request.content_length and request.content_length > max_bytes:
|
|
flash('Die Backup-Datei ist zu groß.', 'error')
|
|
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
|
|
|
|
temp = tempfile.NamedTemporaryFile(
|
|
prefix='cmbnet-restore-',
|
|
suffix='.sqlite3',
|
|
delete=False,
|
|
)
|
|
temp_path = Path(temp.name)
|
|
temp.close()
|
|
source = None
|
|
destination = None
|
|
|
|
try:
|
|
upload.save(temp_path)
|
|
if temp_path.stat().st_size > max_bytes:
|
|
raise ValueError('Die Backup-Datei ist zu groß.')
|
|
if temp_path.stat().st_size < 512:
|
|
raise ValueError('Die Backup-Datei ist leer oder beschädigt.')
|
|
|
|
_validate_backup_file(temp_path)
|
|
|
|
destination = get_db()
|
|
destination.commit()
|
|
source = sqlite3.connect(str(temp_path))
|
|
source.backup(destination)
|
|
destination.commit()
|
|
|
|
# Die Backup-Datei kann im DELETE-Journalmodus erzeugt worden sein.
|
|
# Für den Mehr-Worker-Betrieb wird die Live-Datenbank wieder auf WAL
|
|
# umgestellt.
|
|
destination.execute('PRAGMA journal_mode = WAL')
|
|
destination.execute('PRAGMA synchronous = NORMAL')
|
|
destination.commit()
|
|
|
|
# Nach dem Einspielen fehlende Spalten/Tabellen älterer Backups
|
|
# ergänzen und alle prozesslokalen Caches verwerfen.
|
|
ensure_schema()
|
|
GroupsService.invalidate_all()
|
|
except Exception as exc:
|
|
current_app.logger.exception('Datenbank-Wiederherstellung fehlgeschlagen.')
|
|
try:
|
|
if destination is not None:
|
|
destination.rollback()
|
|
except Exception:
|
|
pass
|
|
flash(f'Wiederherstellung fehlgeschlagen: {exc}', 'error')
|
|
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
|
|
finally:
|
|
try:
|
|
if source is not None:
|
|
source.close()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
temp_path.unlink()
|
|
except OSError:
|
|
pass
|
|
|
|
try:
|
|
notify_reload('Administration: Die Datenbank wurde aus einem Backup wiederhergestellt.')
|
|
except Exception:
|
|
current_app.logger.warning('Reload-Hinweis nach Restore fehlgeschlagen.', exc_info=True)
|
|
|
|
flash('Datenbank wurde erfolgreich wiederhergestellt.', 'success')
|
|
return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant')))
|
|
|
|
|
|
@admin_backup_bp.route('/config/export')
|
|
@role_required('Administrator')
|
|
def export_config(**kwargs):
|
|
"""Liefert alle Konfigurationsparameter als Key:Value-Textdatei."""
|
|
lines = [f'{key}: {value}' for key, value in collect_config_items()]
|
|
body = '\n'.join(lines) + '\n'
|
|
filename = f'cmbnet-config-{datetime.now():%Y%m%d-%H%M%S}.txt'
|
|
response = Response(body, mimetype='text/plain; charset=utf-8')
|
|
response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'
|
|
response.headers['Cache-Control'] = 'no-store'
|
|
return response
|