Merge pull request 'Bundle website and database backups by hosting account' (#25) from feature/account-backup-bundles into main
Reviewed-on: #25
This commit was merged in pull request #25.
This commit is contained in:
commit
a672dd4768
9 files changed
+579
-6
No files matched your search
@@ -354,6 +354,12 @@ Use the MariaDB node commands to create a compressed SQL dump for an individual
|
||||
managed database and restore it to an empty database with the same identity.
|
||||
[Database backup and restore](development.md#back-up-and-restore-a-managed-database)
|
||||
|
||||
## Back up an account's website and databases
|
||||
|
||||
Download the account backup manifest from the panel. Use it to create one
|
||||
ZIP on a single server or bundle native archives from separate nodes.
|
||||
[Account backup and recovery](development.md#back-up-a-hosting-account)
|
||||
|
||||
## Publish local DNS zones from the panel
|
||||
|
||||
Enable the [DNS publishing socket](development.md#enable-local-dns-publishing)
|
||||
|
||||
@@ -857,6 +857,62 @@ entire archive before publishing restored files. Restored files belong
|
||||
to the site account, with the Apache read access recorded in the
|
||||
backup. The website can be recovered while its web services are stopped.
|
||||
|
||||
## Back up a hosting account
|
||||
|
||||
Open the account as an operator and select **Download backup manifest**. The
|
||||
manifest lists the primary website and all database requests for the account.
|
||||
Provision those resources before running the backup. The ZIP archive contains
|
||||
the native website archive and a compressed SQL dump for each listed database.
|
||||
Back up mail, DNS, and panel settings separately.
|
||||
|
||||
On a server hosting both the website and its databases, run the account backup
|
||||
command as root. Add `--socket PATH` when MariaDB uses a custom socket.
|
||||
|
||||
```sh
|
||||
sudo install -d -m 0700 /var/backups/coulobre
|
||||
sudo /opt/coulobre/bin/coulobre-account-backup create \
|
||||
coulobre-account-1-backup.json /var/backups/coulobre/account-1.zip
|
||||
```
|
||||
|
||||
Use a new archive filename. Allow space for the component archives and the
|
||||
finished ZIP while it is assembled. The website and databases are captured
|
||||
in sequence. Pause application writes, SFTP uploads, and schema changes across
|
||||
the components if they need to represent a single point in time.
|
||||
|
||||
### Bundle backups from separate nodes
|
||||
|
||||
Use the [website backup command](#back-up-and-restore-hosted-website-files)
|
||||
on the web node and the [database backup command](#back-up-and-restore-a-managed-database)
|
||||
on each database node. Transfer the resulting files to a root-controlled
|
||||
directory with mode `0600` on every archive. Name the website archive
|
||||
`website.tar.gz` and each SQL dump `database-<suffix>.sql.gz`, for example
|
||||
`database-cms.sql.gz`. Assemble the ZIP with the same account manifest.
|
||||
|
||||
```sh
|
||||
sudo /opt/coulobre/bin/coulobre-account-backup pack \
|
||||
coulobre-account-1-backup.json /var/backups/coulobre/components \
|
||||
/var/backups/coulobre/account-1.zip
|
||||
```
|
||||
|
||||
### Recover backups from the bundle
|
||||
|
||||
Unpack to a new directory on a root-controlled path. The command verifies the
|
||||
ZIP contents and checks the identity and integrity of each compressed
|
||||
component before publishing the directory.
|
||||
|
||||
```sh
|
||||
sudo /opt/coulobre/bin/coulobre-account-backup unpack \
|
||||
/var/backups/coulobre/account-1.zip /var/backups/coulobre/account-1-recovery
|
||||
```
|
||||
|
||||
Use the recovered `website.json` and `website.tar.gz` with `restore-site`.
|
||||
Use each `database-<suffix>.json` and `database-<suffix>.sql.gz` pair with
|
||||
`restore-database`. Transfer the relevant pairs when the destination uses
|
||||
separate nodes. For a full recovery, prepare an empty document root and empty
|
||||
managed databases with the original manifests and restore all components before
|
||||
resuming application traffic. To recover one website file, use the website pair
|
||||
with the existing `restore-site --file` option.
|
||||
|
||||
## Run an isolated PHP test site
|
||||
|
||||
Open a completed preview for the account's current domain and select **Download
|
||||
|
||||
@@ -16,6 +16,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
coulobre-account-backup = "coulobre.account_backup:main"
|
||||
coulobre-database-node = "coulobre.database_node:main"
|
||||
coulobre-directadmin = "coulobre.directadmin:main"
|
||||
coulobre-dns-node = "coulobre.dns_node:main"
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import tarfile
|
||||
import zlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from shutil import copyfileobj
|
||||
from tempfile import NamedTemporaryFile, TemporaryDirectory
|
||||
from zipfile import ZIP_STORED, BadZipFile, ZipFile
|
||||
|
||||
from .database_node import DEFAULT_SOCKET, DatabaseSpec
|
||||
from .node_files import check_root_file, require_root_directory, write_new_file
|
||||
from .web_node import WebSite
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
MANIFEST_KIND = "coulobre_account_backup"
|
||||
MANIFEST_NAME = "manifest.json"
|
||||
MAX_MANIFEST_BYTES = 1024 * 1024
|
||||
CHUNK_BYTES = 1024 * 1024
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AccountBackup:
|
||||
website: WebSite
|
||||
databases: tuple[DatabaseSpec, ...]
|
||||
|
||||
def __post_init__(self):
|
||||
names = set()
|
||||
for database in self.databases:
|
||||
if database.account_id != self.website.account_id:
|
||||
raise ValueError(
|
||||
"All databases must belong to the website's account."
|
||||
)
|
||||
if database.name in names:
|
||||
raise ValueError("The account backup lists a database twice.")
|
||||
names.add(database.name)
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
"version": MANIFEST_VERSION,
|
||||
"kind": MANIFEST_KIND,
|
||||
"website": self.website.manifest(),
|
||||
"databases": [database.manifest() for database in self.databases],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if (
|
||||
not isinstance(data, dict)
|
||||
or data.keys() != {"version", "kind", "website", "databases"}
|
||||
or data["kind"] != MANIFEST_KIND
|
||||
or not isinstance(data["databases"], list)
|
||||
):
|
||||
raise ValueError("Expected a Coulobre account backup manifest.")
|
||||
if (
|
||||
type(data["version"]) is not int
|
||||
or data["version"] != MANIFEST_VERSION
|
||||
):
|
||||
raise ValueError("Unsupported account backup manifest version.")
|
||||
return cls(
|
||||
WebSite.from_manifest(data["website"]),
|
||||
tuple(
|
||||
DatabaseSpec.from_manifest(item) for item in data["databases"]
|
||||
),
|
||||
)
|
||||
|
||||
def components(self):
|
||||
yield self.website, "website.json", "website.tar.gz"
|
||||
for database in self.databases:
|
||||
name = f"database-{database.suffix}"
|
||||
yield database, f"{name}.json", f"{name}.sql.gz"
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="coulobre-account-backup")
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
create = commands.add_parser(
|
||||
"create", help="Back up the website and databases on this server."
|
||||
)
|
||||
create.add_argument("manifest", type=Path)
|
||||
create.add_argument("archive", type=Path)
|
||||
create.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
|
||||
pack = commands.add_parser(
|
||||
"pack", help="Bundle existing native backups from the nodes."
|
||||
)
|
||||
pack.add_argument("manifest", type=Path)
|
||||
pack.add_argument("directory", type=Path)
|
||||
pack.add_argument("archive", type=Path)
|
||||
unpack = commands.add_parser(
|
||||
"unpack", help="Verify and recover the native backups and manifests."
|
||||
)
|
||||
unpack.add_argument("archive", type=Path)
|
||||
unpack.add_argument("directory", type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
if args.command == "unpack":
|
||||
backup = unpack_backup(args.archive, args.directory)
|
||||
else:
|
||||
with args.manifest.open("rb") as source:
|
||||
backup = read_backup_manifest(source)
|
||||
if args.command == "create":
|
||||
create_backup(backup, args.archive, args.socket)
|
||||
else:
|
||||
pack_backup(backup, args.directory, args.archive)
|
||||
except (OSError, ValueError, BadZipFile) as error:
|
||||
parser.exit(1, f"coulobre-account-backup: {error}\n")
|
||||
|
||||
print(json.dumps(backup.manifest(), indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
def read_backup_manifest(source):
|
||||
content = source.read(MAX_MANIFEST_BYTES + 1)
|
||||
if len(content) > MAX_MANIFEST_BYTES:
|
||||
raise ValueError("The account backup manifest exceeds the size limit.")
|
||||
return AccountBackup.from_manifest(json.loads(content))
|
||||
|
||||
|
||||
def private_path(path, *, new=False):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError("Run the account backup command as root.")
|
||||
path = path.absolute()
|
||||
require_root_directory(path.parent)
|
||||
if new and os.path.lexists(path):
|
||||
raise ValueError(f"Choose a new path. {path} already exists.")
|
||||
return path
|
||||
|
||||
|
||||
def create_backup(backup, archive, socket):
|
||||
from .database_node_backup import backup_database
|
||||
from .web_node_backup import backup_website
|
||||
|
||||
archive = private_path(archive, new=True)
|
||||
with TemporaryDirectory(dir=archive.parent) as directory:
|
||||
directory = Path(directory)
|
||||
for resource, _, filename in backup.components():
|
||||
path = directory / filename
|
||||
if isinstance(resource, WebSite):
|
||||
backup_website(resource, path)
|
||||
else:
|
||||
backup_database(resource, socket, path)
|
||||
pack_backup(backup, directory, archive)
|
||||
|
||||
|
||||
def pack_backup(backup, directory, archive):
|
||||
archive = private_path(archive, new=True)
|
||||
directory = directory.absolute()
|
||||
require_root_directory(directory)
|
||||
manifest = manifest_text(backup)
|
||||
with NamedTemporaryFile(dir=archive.parent) as staged:
|
||||
with ZipFile(staged, mode="w", compression=ZIP_STORED) as bundle:
|
||||
bundle.writestr(MANIFEST_NAME, manifest)
|
||||
for resource, _, filename in backup.components():
|
||||
path = directory / filename
|
||||
check_root_file(path, mode=0o600)
|
||||
validate_component(resource, path)
|
||||
bundle.write(path, filename)
|
||||
staged.flush()
|
||||
os.fsync(staged.fileno())
|
||||
os.link(staged.name, archive)
|
||||
|
||||
|
||||
def unpack_backup(archive, directory):
|
||||
archive = private_path(archive)
|
||||
check_root_file(archive, mode=0o600)
|
||||
directory = private_path(directory, new=True)
|
||||
with (
|
||||
ZipFile(archive) as bundle,
|
||||
TemporaryDirectory(dir=directory.parent) as temporary,
|
||||
):
|
||||
staged = Path(temporary)
|
||||
entries = bundle.infolist()
|
||||
if any(
|
||||
entry.compress_type != ZIP_STORED or entry.flag_bits & 1
|
||||
for entry in entries
|
||||
):
|
||||
raise ValueError(
|
||||
"Expected uncompressed entries in the account backup."
|
||||
)
|
||||
manifests = [
|
||||
entry for entry in entries if entry.filename == MANIFEST_NAME
|
||||
]
|
||||
if len(manifests) != 1:
|
||||
raise ValueError("Expected one account backup manifest.")
|
||||
with bundle.open(manifests[0]) as source:
|
||||
backup = read_backup_manifest(source)
|
||||
validate_bundle_entries(entries, backup)
|
||||
write_new_file(
|
||||
staged / MANIFEST_NAME, manifest_text(backup), mode=0o600
|
||||
)
|
||||
for resource, manifest, filename in backup.components():
|
||||
path = staged / filename
|
||||
with bundle.open(filename) as source, path.open("xb") as target:
|
||||
os.fchmod(target.fileno(), 0o600)
|
||||
copyfileobj(source, target, length=CHUNK_BYTES)
|
||||
validate_component(resource, path)
|
||||
write_new_file(
|
||||
staged / manifest, manifest_text(resource), mode=0o600
|
||||
)
|
||||
directory.mkdir(mode=0o700)
|
||||
try:
|
||||
staged.rename(directory)
|
||||
except OSError:
|
||||
directory.rmdir()
|
||||
raise
|
||||
return backup
|
||||
|
||||
|
||||
def manifest_text(resource):
|
||||
text = json.dumps(resource.manifest(), indent=2) + "\n"
|
||||
if len(text.encode("ascii")) > MAX_MANIFEST_BYTES:
|
||||
raise ValueError("The account backup manifest exceeds the size limit.")
|
||||
return text
|
||||
|
||||
|
||||
def validate_bundle_entries(entries, backup):
|
||||
expected = {MANIFEST_NAME}
|
||||
expected.update(filename for _, _, filename in backup.components())
|
||||
if (
|
||||
len(entries) != len(expected)
|
||||
or {entry.filename for entry in entries} != expected
|
||||
):
|
||||
raise ValueError(
|
||||
"The account backup has missing or unexpected entries."
|
||||
)
|
||||
|
||||
|
||||
def validate_component(resource, path):
|
||||
from .database_node_backup import validate_dump_header
|
||||
from .web_node_backup import validate_metadata
|
||||
|
||||
try:
|
||||
with gzip.open(path, "rb") as data:
|
||||
if isinstance(resource, WebSite):
|
||||
with tarfile.open(fileobj=data, mode="r|") as archive:
|
||||
validate_metadata(archive, archive.next(), resource)
|
||||
else:
|
||||
validate_dump_header(resource, data)
|
||||
if not data.read(1):
|
||||
raise ValueError(
|
||||
"The MariaDB backup is missing its SQL dump."
|
||||
)
|
||||
while data.read(CHUNK_BYTES):
|
||||
pass
|
||||
except (EOFError, gzip.BadGzipFile, tarfile.TarError, zlib.error):
|
||||
raise ValueError(
|
||||
f"The native backup {path.name} is damaged."
|
||||
) from None
|
||||
except ValueError as error:
|
||||
raise ValueError(f"Could not validate {path.name}. {error}") from None
|
||||
@@ -127,11 +127,7 @@ def backup_header(database):
|
||||
def read_dump(database, archive, destination):
|
||||
try:
|
||||
with gzip.open(archive, "rb") as data:
|
||||
header = data.readline(MAX_HEADER_BYTES + 1)
|
||||
if header != backup_header(database):
|
||||
raise ValueError(
|
||||
"Expected a native dump for this MariaDB database."
|
||||
)
|
||||
validate_dump_header(database, data)
|
||||
copyfileobj(data, destination, length=1024 * 1024)
|
||||
except (EOFError, gzip.BadGzipFile, zlib.error):
|
||||
raise ValueError(
|
||||
@@ -141,6 +137,11 @@ def read_dump(database, archive, destination):
|
||||
raise ValueError("The MariaDB backup is missing its SQL dump.")
|
||||
|
||||
|
||||
def validate_dump_header(database, data):
|
||||
if data.readline(MAX_HEADER_BYTES + 1) != backup_header(database):
|
||||
raise ValueError("Expected a native dump for this MariaDB database.")
|
||||
|
||||
|
||||
def check_definers(cursor, name):
|
||||
expected = f"{name}@localhost"
|
||||
for table, schema in DEFINER_OBJECTS:
|
||||
|
||||
@@ -7,11 +7,14 @@
|
||||
<h1>{{ account.name }}</h1>
|
||||
<p class="heading-meta domain">{{ account.primary_domain }}</p>
|
||||
</div>
|
||||
{% if manage_sftp or is_operator and perms.hosting.change_hostingaccount %}
|
||||
{% if manage_sftp or export_backup_manifest or is_operator and perms.hosting.change_hostingaccount %}
|
||||
<div class="form-actions">
|
||||
{% if manage_sftp %}
|
||||
<a class="button secondary" href="{% url 'panel:sftp_keys' account.pk %}">SFTP access</a>
|
||||
{% endif %}
|
||||
{% if export_backup_manifest %}
|
||||
<a class="button secondary" href="{% url 'panel:account_backup_manifest' account.pk %}">Download backup manifest</a>
|
||||
{% endif %}
|
||||
{% if is_operator and perms.hosting.change_hostingaccount %}
|
||||
<a class="button secondary" href="{% url 'panel:account_edit' account.pk %}">Edit account</a>
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import gzip
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tarfile
|
||||
from contextlib import redirect_stdout
|
||||
from io import StringIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest.mock import patch
|
||||
from zipfile import ZipFile
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre import account_backup
|
||||
from coulobre.account_backup import AccountBackup
|
||||
from coulobre.database_node import DatabaseSpec
|
||||
from coulobre.database_node_backup import backup_header
|
||||
from coulobre.web_node import WebSite
|
||||
from coulobre.web_node_backup import write_metadata
|
||||
|
||||
from .models import HostingAccount, HostingDatabase, Reseller
|
||||
|
||||
|
||||
class AccountBackupManifestTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_user("operator")
|
||||
cls.reseller = users.create_user("reseller")
|
||||
permissions = Permission.objects.filter(
|
||||
content_type__app_label="hosting",
|
||||
codename__in=(
|
||||
"view_hostingaccount",
|
||||
"view_webprovisioningplan",
|
||||
"view_hostingdatabase",
|
||||
),
|
||||
)
|
||||
cls.operator.user_permissions.set(permissions)
|
||||
cls.reseller.user_permissions.set(permissions)
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Site",
|
||||
primary_domain="site.example",
|
||||
reseller=Reseller.objects.create(user=cls.reseller),
|
||||
)
|
||||
other_account = HostingAccount.objects.create(
|
||||
name="Other", primary_domain="other.example"
|
||||
)
|
||||
cls.shop = HostingDatabase.objects.create(
|
||||
account=cls.account, suffix="shop"
|
||||
)
|
||||
cls.cms = HostingDatabase.objects.create(
|
||||
account=cls.account, suffix="cms"
|
||||
)
|
||||
HostingDatabase.objects.create(account=other_account, suffix="other")
|
||||
|
||||
def setUp(self):
|
||||
self.url = reverse(
|
||||
"panel:account_backup_manifest", args=[self.account.pk]
|
||||
)
|
||||
|
||||
def test_operator_can_download_inventory_for_one_account(self):
|
||||
self.client.force_login(self.operator)
|
||||
response = self.client.get(self.url)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response["Cache-Control"], "private, no-store")
|
||||
self.assertIn("attachment", response["Content-Disposition"])
|
||||
self.assertEqual(
|
||||
AccountBackup.from_manifest(response.json()),
|
||||
AccountBackup(
|
||||
WebSite(self.account.pk, self.account.primary_domain),
|
||||
(self.cms.spec, self.shop.spec),
|
||||
),
|
||||
)
|
||||
self.assertContains(
|
||||
self.client.get(self.account.get_absolute_url()), self.url
|
||||
)
|
||||
|
||||
def test_reseller_cannot_export_even_with_resource_view_permissions(self):
|
||||
self.client.force_login(self.reseller)
|
||||
|
||||
self.assertEqual(self.client.get(self.url).status_code, 403)
|
||||
self.assertNotContains(
|
||||
self.client.get(self.account.get_absolute_url()), self.url
|
||||
)
|
||||
|
||||
def test_operator_needs_database_view_permission(self):
|
||||
permission = Permission.objects.get(
|
||||
content_type__app_label="hosting", codename="view_hostingdatabase"
|
||||
)
|
||||
self.operator.user_permissions.remove(permission)
|
||||
self.client.force_login(self.operator)
|
||||
|
||||
self.assertEqual(self.client.get(self.url).status_code, 403)
|
||||
|
||||
|
||||
class AccountBackupCommandTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
self.root = Path(self.enterContext(TemporaryDirectory()))
|
||||
self.site = WebSite(42, "site.example")
|
||||
self.database = DatabaseSpec(42, "cms")
|
||||
self.backup = AccountBackup(self.site, (self.database,))
|
||||
self.manifest = self.root / "account.json"
|
||||
self.manifest.write_text(json.dumps(self.backup.manifest()))
|
||||
self.archive = self.root / "account.zip"
|
||||
self.restored = self.root / "restored"
|
||||
self.enterContext(patch.object(os, "geteuid", return_value=0))
|
||||
self.enterContext(
|
||||
patch.object(account_backup, "require_root_directory")
|
||||
)
|
||||
self.enterContext(patch.object(account_backup, "check_root_file"))
|
||||
|
||||
def run_backup(self, *args):
|
||||
with redirect_stdout(StringIO()):
|
||||
self.assertEqual(
|
||||
account_backup.main([str(arg) for arg in args]), 0
|
||||
)
|
||||
|
||||
def write_website(self, site, path):
|
||||
with tarfile.open(path, mode="w:gz") as archive:
|
||||
write_metadata(archive, site)
|
||||
tree = tarfile.TarInfo("public")
|
||||
tree.type = tarfile.DIRTYPE
|
||||
archive.addfile(tree)
|
||||
|
||||
def write_database(self, database, socket, path):
|
||||
path.write_bytes(
|
||||
gzip.compress(backup_header(database) + b"SELECT 1;\n")
|
||||
)
|
||||
|
||||
def test_create_and_unpack_recover_the_native_archives_and_manifests(self):
|
||||
with (
|
||||
patch(
|
||||
"coulobre.web_node_backup.backup_website",
|
||||
side_effect=self.write_website,
|
||||
),
|
||||
patch(
|
||||
"coulobre.database_node_backup.backup_database",
|
||||
side_effect=self.write_database,
|
||||
) as dump,
|
||||
):
|
||||
self.run_backup(
|
||||
"create", self.manifest, self.archive, "--socket", "/db.sock"
|
||||
)
|
||||
self.assertEqual(
|
||||
dump.call_args.args[:2], (self.database, Path("/db.sock"))
|
||||
)
|
||||
self.run_backup("unpack", self.archive, self.restored)
|
||||
|
||||
self.assertEqual(stat.S_IMODE(self.archive.stat().st_mode), 0o600)
|
||||
self.assertEqual(stat.S_IMODE(self.restored.stat().st_mode), 0o700)
|
||||
for resource, manifest, filename in self.backup.components():
|
||||
self.assertEqual(
|
||||
json.loads((self.restored / manifest).read_text()),
|
||||
resource.manifest(),
|
||||
)
|
||||
self.assertEqual(
|
||||
stat.S_IMODE((self.restored / filename).stat().st_mode), 0o600
|
||||
)
|
||||
self.assertEqual(
|
||||
gzip.decompress(
|
||||
(self.restored / "database-cms.sql.gz").read_bytes()
|
||||
),
|
||||
backup_header(self.database) + b"SELECT 1;\n",
|
||||
)
|
||||
|
||||
def test_pack_rejects_an_archive_from_another_account(self):
|
||||
self.write_website(self.site, self.root / "website.tar.gz")
|
||||
self.write_database(
|
||||
DatabaseSpec(43, "cms"), None, self.root / "database-cms.sql.gz"
|
||||
)
|
||||
|
||||
with self.assertRaisesMessage(ValueError, "for this MariaDB database"):
|
||||
account_backup.pack_backup(self.backup, self.root, self.archive)
|
||||
|
||||
self.assertFalse(self.archive.exists())
|
||||
|
||||
def test_pack_rejects_a_truncated_native_archive(self):
|
||||
path = self.root / "website.tar.gz"
|
||||
self.write_website(self.site, path)
|
||||
path.write_bytes(path.read_bytes()[:-4])
|
||||
|
||||
with self.assertRaisesMessage(ValueError, "website.tar.gz is damaged"):
|
||||
account_backup.pack_backup(
|
||||
AccountBackup(self.site, ()), self.root, self.archive
|
||||
)
|
||||
|
||||
self.assertFalse(self.archive.exists())
|
||||
|
||||
def test_pack_and_unpack_support_an_account_without_databases(self):
|
||||
backup = AccountBackup(self.site, ())
|
||||
self.manifest.write_text(json.dumps(backup.manifest()))
|
||||
self.write_website(self.site, self.root / "website.tar.gz")
|
||||
self.run_backup("pack", self.manifest, self.root, self.archive)
|
||||
self.run_backup("unpack", self.archive, self.restored)
|
||||
|
||||
self.assertEqual(
|
||||
{path.name for path in self.restored.iterdir()},
|
||||
{"manifest.json", "website.json", "website.tar.gz"},
|
||||
)
|
||||
|
||||
def test_unpack_checks_every_component_before_publishing(self):
|
||||
website = self.root / "website.tar.gz"
|
||||
self.write_website(self.site, website)
|
||||
with ZipFile(self.archive, mode="w") as bundle:
|
||||
bundle.write(self.manifest, "manifest.json")
|
||||
bundle.write(website, "website.tar.gz")
|
||||
bundle.writestr("database-cms.sql.gz", b"incomplete")
|
||||
|
||||
with self.assertRaisesMessage(
|
||||
ValueError, "database-cms.sql.gz is damaged"
|
||||
):
|
||||
account_backup.unpack_backup(self.archive, self.restored)
|
||||
|
||||
self.assertFalse(self.restored.exists())
|
||||
@@ -20,6 +20,11 @@ urlpatterns = [
|
||||
"accounts/new/", views.AccountCreate.as_view(), name="account_create"
|
||||
),
|
||||
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
|
||||
path(
|
||||
"accounts/<int:pk>/backup-manifest/",
|
||||
views.DownloadAccountBackupManifest.as_view(),
|
||||
name="account_backup_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/sftp/",
|
||||
views.SiteSFTPKeys.as_view(),
|
||||
|
||||
@@ -26,9 +26,11 @@ from django.views.generic import (
|
||||
)
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.account_backup import AccountBackup
|
||||
from coulobre.dns_node import MAX_SOA_SERIAL
|
||||
from coulobre.mail_node import INVALID_LOCAL_PART
|
||||
from coulobre.sftp_keys import public_key_fingerprint
|
||||
from coulobre.web_node import WebSite
|
||||
|
||||
from .access import (
|
||||
OperatorOnlyMixin,
|
||||
@@ -78,6 +80,7 @@ VIEW_CUSTOMERS = "hosting.view_customer"
|
||||
VIEW_DATABASES = "hosting.view_hostingdatabase"
|
||||
VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
|
||||
VIEW_MAILBOXES = "hosting.view_hostingmailbox"
|
||||
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
|
||||
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
|
||||
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
|
||||
PROVISION_DATABASE = (
|
||||
@@ -229,6 +232,9 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
reseller = reseller_for_user(user)
|
||||
customer = customer_for_user(user)
|
||||
tenant = reseller is not None or customer is not None
|
||||
context["export_backup_manifest"] = not tenant and user.has_perms(
|
||||
EXPORT_BACKUP_MANIFEST
|
||||
)
|
||||
context["manage_sftp"] = (
|
||||
settings.LOCAL_WEB_SFTP
|
||||
and can_manage_sftp(user)
|
||||
@@ -276,6 +282,29 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
return context
|
||||
|
||||
|
||||
class DownloadAccountBackupManifest(
|
||||
OperatorOnlyMixin, PermissionRequiredMixin, View
|
||||
):
|
||||
permission_required = EXPORT_BACKUP_MANIFEST
|
||||
|
||||
def get(self, request, pk):
|
||||
account = get_object_or_404(HostingAccount, pk=pk)
|
||||
backup = AccountBackup(
|
||||
WebSite(account.pk, account.primary_domain),
|
||||
tuple(database.spec for database in account.databases.all()),
|
||||
)
|
||||
return JsonResponse(
|
||||
backup.manifest(),
|
||||
headers={
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": (
|
||||
"attachment; "
|
||||
f'filename="coulobre-account-{account.pk}-backup.json"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class SiteSFTPKeys(PermissionRequiredMixin, FormView):
|
||||
form_class = SFTPKeyUploadForm
|
||||
template_name = "hosting/sftp_keys.html"
|
||||
|
||||
Reference in new issue
Block a user