mirror of
https://github.com/retspen/webvirtcloud
synced 2026-12-03 17:36:05 +00:00
feat(appsettings): the panel backup dumps a PostgreSQL database
With PostgreSQL the daily backup left the database out and only warned. It now writes a pg_dump in its custom format as db.pgdump and fails when pg_dump is missing or the dump fails. The Docker image ships postgresql-client; the restore and move steps say how to put the dump back.
This commit is contained in:
parent
b4c7ecddc4
commit
2b5d0ac80e
6 changed files with 67 additions and 19 deletions
|
|
@ -11,6 +11,7 @@ RUN apt-get update -qq \
|
|||
libvirt0 \
|
||||
nginx \
|
||||
openssh-client \
|
||||
postgresql-client \
|
||||
python3 \
|
||||
supervisor \
|
||||
tzdata \
|
||||
|
|
|
|||
|
|
@ -15,8 +15,8 @@ PREFIX = "webvirtcloud-backup-"
|
|||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = ("Copy the database, secret key, worker id, local settings and the SSH keys and TLS certificates of the "
|
||||
"panel's user into a new directory in backups/, then delete all but the newest --keep backups.")
|
||||
help = ("Copy the database (sqlite) or dump it (PostgreSQL), the secret key, worker id, local settings and the "
|
||||
"SSH keys and TLS certificates of the panel's user into a new directory in backups/, then delete all but the newest --keep backups.")
|
||||
|
||||
def add_arguments(self, parser):
|
||||
parser.add_argument("--keep", type=int, default=7, help="how many backups to keep (default 7)")
|
||||
|
|
@ -65,6 +65,8 @@ class Command(BaseCommand):
|
|||
result = copy.execute("PRAGMA integrity_check").fetchone()[0]
|
||||
if result != "ok":
|
||||
raise CommandError(f"The copy of the database is damaged: {result}")
|
||||
elif database["ENGINE"] == "django.db.backends.postgresql":
|
||||
self.dump_postgresql(database, to / "db.pgdump")
|
||||
else:
|
||||
self.stderr.write("The database is not sqlite and is not in the backup: back it up with its own tools.")
|
||||
# the key in use: SECRET_KEY from the environment has no data/secret_key
|
||||
|
|
@ -87,3 +89,16 @@ class Command(BaseCommand):
|
|||
commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=settings.BASE_DIR, capture_output=True, text=True)
|
||||
if commit.returncode == 0:
|
||||
(to / "commit").write_text(commit.stdout)
|
||||
|
||||
@staticmethod
|
||||
def dump_postgresql(database, to):
|
||||
"""pg_dump's own format, which pg_restore reads; a consistent state while the panel writes."""
|
||||
if shutil.which("pg_dump") is None:
|
||||
raise CommandError("pg_dump is not installed: install the PostgreSQL client (postgresql-client)")
|
||||
# libpq reads the password and the connect timeout from the environment, not the command line
|
||||
env = {**os.environ, "PGPASSWORD": database["PASSWORD"], "PGCONNECT_TIMEOUT": "10"}
|
||||
dump = subprocess.run(["pg_dump", "--format=custom", f"--file={to}", f"--host={database['HOST']}",
|
||||
f"--port={database['PORT']}", f"--username={database['USER']}", f"--dbname={database['NAME']}"],
|
||||
env=env, capture_output=True, text=True)
|
||||
if dump.returncode != 0:
|
||||
raise CommandError(f"pg_dump failed: {dump.stderr.strip()}")
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@ from datetime import datetime
|
|||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from unittest import skipUnless
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.core.management import call_command
|
||||
|
|
@ -21,8 +21,6 @@ from django.test import SimpleTestCase, override_settings
|
|||
from appsettings.management.commands.backup import Command
|
||||
|
||||
|
||||
SQLITE_ONLY = skipUnless(connection.vendor == "sqlite", "the backup copies only a sqlite database")
|
||||
|
||||
|
||||
class BackupTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
|
|
@ -49,7 +47,8 @@ class BackupTests(SimpleTestCase):
|
|||
db.execute("CREATE TABLE computes_compute (name)")
|
||||
db.execute("INSERT INTO computes_compute VALUES ('kept')")
|
||||
db.commit()
|
||||
name = patch.dict(connection.settings_dict, NAME=str(self.base / "db.sqlite3"))
|
||||
# a sqlite panel also on the PostgreSQL test run; the PostgreSQL tests patch their own
|
||||
name = patch.dict(connection.settings_dict, ENGINE="django.db.backends.sqlite3", NAME=str(self.base / "db.sqlite3"))
|
||||
name.start()
|
||||
self.addCleanup(name.stop)
|
||||
|
||||
|
|
@ -61,7 +60,6 @@ class BackupTests(SimpleTestCase):
|
|||
def kept(self):
|
||||
return sorted(p.name for p in self.backups.iterdir() if p.name != ".lock")
|
||||
|
||||
@SQLITE_ONLY
|
||||
def test_a_backup_holds_the_database_keys_and_settings_for_the_panel_user_only(self):
|
||||
backup = self.backup()
|
||||
with closing(sqlite3.connect(backup / "db.sqlite3")) as db:
|
||||
|
|
@ -110,7 +108,6 @@ class BackupTests(SimpleTestCase):
|
|||
self.backup("--keep", "1")
|
||||
self.assertEqual(self.kept(), ["webvirtcloud-backup-20260101-000000"])
|
||||
|
||||
@SQLITE_ONLY
|
||||
def test_a_damaged_copy_fails(self):
|
||||
with patch("appsettings.management.commands.backup.sqlite3") as sqlite, \
|
||||
self.assertRaisesRegex(CommandError, "damaged: row 3 missing from index"):
|
||||
|
|
@ -126,10 +123,34 @@ class BackupTests(SimpleTestCase):
|
|||
self.backup()
|
||||
self.assertEqual(self.kept(), [])
|
||||
|
||||
def test_a_database_other_than_sqlite_is_left_out(self):
|
||||
errors = StringIO()
|
||||
with patch.dict(connection.settings_dict, ENGINE="django.db.backends.postgresql"):
|
||||
call_command("backup", stdout=StringIO(), stderr=errors)
|
||||
backup = self.backups / self.kept()[0]
|
||||
self.assertNotIn("db.sqlite3", [p.name for p in backup.iterdir()])
|
||||
self.assertIn("back it up with its own tools", errors.getvalue())
|
||||
def postgresql(self):
|
||||
return patch.dict(connection.settings_dict, ENGINE="django.db.backends.postgresql", HOST="192.0.2.10",
|
||||
PORT="5432", NAME="webvirtcloud", USER="webvirtcloud", PASSWORD="db password")
|
||||
|
||||
def test_a_postgresql_database_is_dumped_with_its_password_out_of_the_command_line(self):
|
||||
def pg_dump(args, env, **kwargs):
|
||||
Path(args[2].removeprefix("--file=")).write_bytes(b"PGDMP")
|
||||
return subprocess.CompletedProcess(args, 0, "", "")
|
||||
|
||||
with self.postgresql(), patch("shutil.which", return_value="/usr/bin/pg_dump"), \
|
||||
patch("subprocess.run", side_effect=pg_dump) as run:
|
||||
backup = self.backup()
|
||||
args, env = run.call_args.args[0], run.call_args.kwargs["env"]
|
||||
self.assertEqual(args, ["pg_dump", "--format=custom", f"--file={backup.parent}/.{backup.name}/db.pgdump",
|
||||
"--host=192.0.2.10", "--port=5432", "--username=webvirtcloud", "--dbname=webvirtcloud"])
|
||||
self.assertEqual(env["PGPASSWORD"], "db password")
|
||||
self.assertEqual((backup / "db.pgdump").read_bytes(), b"PGDMP")
|
||||
self.assertEqual(oct((backup / "db.pgdump").stat().st_mode & 0o777), "0o600")
|
||||
|
||||
def test_a_failed_dump_fails_the_backup(self):
|
||||
failed = subprocess.CompletedProcess([], 1, "", "pg_dump: error: server version mismatch\n")
|
||||
with self.postgresql(), patch("shutil.which", return_value="/usr/bin/pg_dump"), \
|
||||
patch("subprocess.run", return_value=failed), self.assertRaisesRegex(CommandError, "server version mismatch"):
|
||||
self.backup()
|
||||
self.assertEqual(self.kept(), [])
|
||||
|
||||
def test_a_postgresql_database_without_pg_dump_fails_the_backup(self):
|
||||
with self.postgresql(), patch("shutil.which", return_value=None), \
|
||||
self.assertRaisesRegex(CommandError, "install the PostgreSQL client"):
|
||||
self.backup()
|
||||
self.assertEqual(self.kept(), [])
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@
|
|||
|
||||
The panel backs itself up every day at 03:15 (cron in Docker; otherwise `webvirt-backup.timer`, within 10 minutes after and at the next boot if the server was off) into a new directory under `/srv/webvirtcloud/backups`, in Docker the `webvirtcloud-backups` volume, and keeps the newest 7. A backup holds:
|
||||
|
||||
- `db.sqlite3`: a consistent copy taken while the panel runs, checked with `PRAGMA integrity_check`; with PostgreSQL it is left out, so back up that database yourself
|
||||
- `db.sqlite3`: a consistent copy taken while the panel runs, checked with `PRAGMA integrity_check`
|
||||
- `db.pgdump` instead, with PostgreSQL: a `pg_dump` of the database in its custom format. The Docker image has `pg_dump`; otherwise install the PostgreSQL client (`postgresql-client` on Debian and Ubuntu, `postgresql` on RHEL), of the server's major version or newer. Without it the backup fails
|
||||
- `secret_key`, `node_id` and `local_settings.py`
|
||||
- `ssh/`: the SSH keys of the panel's user, which the SSH computes accept
|
||||
- `pki/`: the TLS client certificates of the panel's user, which the TLS computes accept
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ What an update from an older version changes for operators and users. To run the
|
|||
- gstfsd does only what the panel signs with the host's key: it does not start without `GSTFSD_KEY` in `/etc/default/webvirt-gstfsd`. On every compute, update gstfsd and its unit and make the key as in [Adding a Compute Node, step 3](compute-nodes.md#3-install-gstfsd) (a remote panel's `GSTFSD_BIND_HOST` and `GSTFSD_ALLOW_REMOTE` move into that file from `systemctl edit webvirt-gstfsd`), then enter the key on each compute's edit page.
|
||||
- LDAP login's packages are in `conf/requirements-ldap.txt` and no longer installed by default, nor their build headers by the installer; the Docker image keeps them. An existing virtualenv keeps them, but only installing that file updates them (see [LDAP](ldap.md)).
|
||||
- The themes ship compiled; picking one on the Settings page only saves its name, and the "Theme SASS Path" setting is gone. Browsers revalidate static files on each load: files cached before the update can stay until a hard reload (Ctrl+F5) of each page; an external caching proxy may need a purge.
|
||||
- The panel backs itself up every day ([Backups](backups.md)); in Docker into a new volume, `webvirtcloud-backups`.
|
||||
- The panel backs itself up every day ([Backups](backups.md)); in Docker into a new volume, `webvirtcloud-backups`. With PostgreSQL the backup holds a `pg_dump` of the database and fails without `pg_dump`: outside Docker, install the PostgreSQL client.
|
||||
- The Docker image is built on Ubuntu 26.04 LTS (Python 3.14, libvirt 12) instead of 24.04; `docker compose up -d --build` rebuilds it.
|
||||
- New passwords must pass Django's password validators: at least 8 characters, not a common password, not only digits, not like the user's name or e-mail. Existing passwords keep working.
|
||||
- In Docker, the TLS client certificates of TLS computes are kept in a new volume, `webvirtcloud-pki` (`/var/www/.pki`), and backed up; put them there once ([Adding a Compute Node, TLS](compute-nodes.md#tls)).
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ From a root shell:
|
|||
|
||||
## Restore and rollback
|
||||
|
||||
Restoring puts back the database as it was at the backup; changes made since are lost. Migrations are not reversed. This covers sqlite; restore a PostgreSQL database from your own backup before rolling back the code. Set `b` to the backup directory to restore. To restore the database without rolling back the code, leave out the `build` line and every line that takes another file from `$b`: the commit, `local-migrations.tar`, `settings.py` and `local_settings.py`, the nginx config and `/etc/default/webvirtcloud`.
|
||||
Restoring puts back the database as it was at the backup; changes made since are lost. Migrations are not reversed. With PostgreSQL, restore the database from the backup's `db.pgdump` before rolling back the code, as in [Restoring a PostgreSQL database](#restoring-a-postgresql-database), and leave out the line below that restores `db.sqlite3`. Set `b` to the backup directory to restore. To restore the database without rolling back the code, leave out the `build` line and every line that takes another file from `$b`: the commit, `local-migrations.tar`, `settings.py` and `local_settings.py`, the nginx config and `/etc/default/webvirtcloud`.
|
||||
|
||||
Docker, in the directory you installed from:
|
||||
|
||||
|
|
@ -123,9 +123,19 @@ nginx -t && systemctl reload nginx && systemctl start webvirt-cloud webvirt-novn
|
|||
|
||||
A version from before v3.0.0 has no worker: `systemctl disable --now webvirt-worker`. A rollback keeps the systemd units, and drops what a stopped `update.sh` kept to go on with (`data/.update-backup`). A rollback leaves the clone on a detached HEAD at the restored commit; `update.sh` records that commit before it switches back to `master`.
|
||||
|
||||
### Restoring a PostgreSQL database
|
||||
|
||||
With the panel stopped, from a shell with the PostgreSQL client and the `WEBVIRTCLOUD_DB_*` values the panel uses. The first command empties the database, also of tables a later version added:
|
||||
|
||||
```bash
|
||||
export PGPASSWORD="$WEBVIRTCLOUD_DB_PASSWORD" &&
|
||||
psql -h "$WEBVIRTCLOUD_DB_HOST" -U webvirtcloud -d webvirtcloud -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public" &&
|
||||
pg_restore --no-owner -h "$WEBVIRTCLOUD_DB_HOST" -U webvirtcloud -d webvirtcloud "$b/db.pgdump"
|
||||
```
|
||||
|
||||
## Moving to a new machine
|
||||
|
||||
A [backup](backups.md) moves the panel to a new machine, or back onto lost volumes: the database, the secret key (signed-in users stay signed in), the worker's id and the SSH keys and TLS certificates the computes accept. Install the panel there first, the same version or a newer one, then copy the backup directory over and set `b` to it. The backup does not hold `docker-compose.override.yml`, the nginx config or `/etc/default/webvirtcloud`: bring your own lines over yourself. Users sign in with their passwords from the backup; the new installation's `data/admin_password` no longer applies. The backup's `secret_key` is the key in use, also one set as `SECRET_KEY` in the environment. With PostgreSQL, restore that database yourself and leave out the line below that restores `db.sqlite3` (the backup has none), and stop the old panel before the new one starts: both would run the jobs of the one database.
|
||||
A [backup](backups.md) moves the panel to a new machine, or back onto lost volumes: the database, the secret key (signed-in users stay signed in), the worker's id and the SSH keys and TLS certificates the computes accept. Install the panel there first, the same version or a newer one, then copy the backup directory over and set `b` to it. The backup does not hold `docker-compose.override.yml`, the nginx config or `/etc/default/webvirtcloud`: bring your own lines over yourself. Users sign in with their passwords from the backup; the new installation's `data/admin_password` no longer applies. The backup's `secret_key` is the key in use, also one set as `SECRET_KEY` in the environment. With PostgreSQL, restore the backup's `db.pgdump` as in [Restoring a PostgreSQL database](#restoring-a-postgresql-database) and leave out the line below that restores `db.sqlite3` (the backup has none); stop the old panel before the new one starts: both would run the jobs of the one database.
|
||||
|
||||
Docker, in the directory you installed from:
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue