Start local account backups from Coulobre Panel #27

Merged
parkel merged 2 commits from feature/panel-account-backups into main 2026-11-21 12:36:17 +01:00
19 changed files with 691 additions and 15 deletions

No files matched your search

+1
View File
@@ -14,3 +14,4 @@ COULOBRE_BROKER_URL=amqp://coulobre:@127.0.0.1:5672/coulobre
# COULOBRE_LOCAL_DATABASE_PROVISIONING=1 # COULOBRE_LOCAL_DATABASE_PROVISIONING=1
# COULOBRE_LOCAL_DNS_PUBLISHING=1 # COULOBRE_LOCAL_DNS_PUBLISHING=1
# COULOBRE_LOCAL_MAILBOX_PROVISIONING=1 # COULOBRE_LOCAL_MAILBOX_PROVISIONING=1
# COULOBRE_LOCAL_ACCOUNT_BACKUPS=1
@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre local account backup socket
[Socket]
ListenStream=/run/coulobre-account-backup.sock
SocketUser=root
SocketGroup=coulobre-backup-requests
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,21 @@
[Unit]
Description=Coulobre local account backup request
After=mariadb.service
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/account-backups coulobre/database-node
StateDirectoryMode=0700
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-account-backup create-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=30min
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
@@ -0,0 +1,26 @@
[Unit]
Description=Coulobre Panel local account backup worker
Requires=coulobre-account-backup.socket
Wants=network-online.target
After=network-online.target coulobre-account-backup.socket mariadb.service rabbitmq-server.service
[Service]
Type=exec
User=coulobre-backup-worker
Group=coulobre-backup-worker
SupplementaryGroups=coulobre-backup-requests
EnvironmentFile=/etc/coulobre/panel.env
WorkingDirectory=/opt/coulobre
UMask=0077
ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --queues=coulobre-account-backups --hostname=backup-worker@%H --concurrency=1 --prefetch-multiplier=1
KillMode=mixed
TimeoutStopSec=31min
Restart=on-failure
RestartSec=5s
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
[Install]
WantedBy=multi-user.target
+35
View File
@@ -360,6 +360,41 @@ 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. ZIP on a single server or bundle native archives from separate nodes.
[Account backup and recovery](development.md#back-up-a-hosting-account) [Account backup and recovery](development.md#back-up-a-hosting-account)
### Start local account backups from the panel
Enable this option when the panel, website, and the account's MariaDB
databases run on the same server. The backup service uses the default MariaDB
socket and the website and database registries on that server.
```sh
sudo groupadd --system coulobre-backup-requests
sudo useradd --system --user-group --no-create-home --home-dir /nonexistent \
--shell /usr/sbin/nologin coulobre-backup-worker
sudo install -m 0644 deploy/systemd/coulobre-account-backup.socket \
deploy/systemd/coulobre-account-backup@.service \
deploy/systemd/coulobre-backup-worker.service /etc/systemd/system/
sudo systemctl daemon-reload
```
Set `COULOBRE_LOCAL_ACCOUNT_BACKUPS=1` in `/etc/coulobre/panel.env`, then apply
pending migrations and restart the panel services.
```sh
panel_manage migrate --noinput
sudo systemctl restart coulobre-panel coulobre-worker coulobre-beat
sudo systemctl enable --now coulobre-backup-worker.service
```
Open the account and select **Create backup**. Operators need permission to
view hosting accounts, Apache previews, and database requests, plus
**Can add account backup job**. Reload the page to see the status and the path
of the completed ZIP. Only one backup can be queued or running for an account
at a time. The node gives each backup up to 30 minutes.
Archives are stored under `/var/lib/coulobre/account-backups/` with root-only
access. Retrieve archives and manage their retention on the server. Recovery
uses the existing [account bundle commands](development.md#recover-backups-from-the-bundle).
## Publish local DNS zones from the panel ## Publish local DNS zones from the panel
Enable the [DNS publishing socket](development.md#enable-local-dns-publishing) Enable the [DNS publishing socket](development.md#enable-local-dns-publishing)
+4
View File
@@ -898,6 +898,10 @@ Provision those resources before running the backup. The ZIP archive contains
the native website archive and a compressed SQL dump for each listed database. the native website archive and a compressed SQL dump for each listed database.
Back up mail, DNS, and panel settings separately. Back up mail, DNS, and panel settings separately.
On a single-server installation, operators can also start a backup and view
its status directly on the account page.
[Enable account backups in the panel](deployment.md#start-local-account-backups-from-the-panel)
On a server hosting both the website and its databases, run the account backup 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. command as root. Add `--socket PATH` when MariaDB uses a custom socket.
+8
View File
@@ -93,8 +93,16 @@ def main(argv=None):
) )
unpack.add_argument("archive", type=Path) unpack.add_argument("archive", type=Path)
unpack.add_argument("directory", type=Path) unpack.add_argument("directory", type=Path)
commands.add_parser(
"create-request", help="Create a local backup for the panel worker."
)
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.command == "create-request":
from .account_backup_request import serve_backup_request
return serve_backup_request()
try: try:
if args.command == "unpack": if args.command == "unpack":
backup = unpack_backup(args.archive, args.directory) backup = unpack_backup(args.archive, args.directory)
+108
View File
@@ -0,0 +1,108 @@
import os
from dataclasses import dataclass
from pathlib import Path
from uuid import UUID
from zipfile import BadZipFile, ZipFile
from .account_backup import (
MANIFEST_NAME,
MAX_MANIFEST_BYTES,
AccountBackup,
create_backup,
read_backup_manifest,
)
from .database_node import DEFAULT_SOCKET
from .node_files import check_root_file, require_root_directory
from .node_requests import serve_apply_request
REQUEST_VERSION = 1
BACKUP_DIRECTORY = Path("/var/lib/coulobre/account-backups")
BACKUP_SOCKET = "/run/coulobre-account-backup.sock"
BACKUP_TIMEOUT_SECONDS = 30 * 60
@dataclass(frozen=True)
class AccountBackupRequest:
backup_id: UUID
backup: AccountBackup
@classmethod
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys() != {"version", "backup_id", "backup"}
or type(data["version"]) is not int
or data["version"] != REQUEST_VERSION
or not isinstance(data["backup_id"], str)
):
raise ValueError("Expected a local account backup request.")
backup_id = UUID(data["backup_id"])
if str(backup_id) != data["backup_id"]:
raise ValueError("Expected a canonical backup ID.")
return cls(backup_id, AccountBackup.from_manifest(data["backup"]))
def manifest(self):
return {
"version": REQUEST_VERSION,
"backup_id": str(self.backup_id),
"backup": self.backup.manifest(),
}
def identity(self):
return {
"version": REQUEST_VERSION,
"backup_id": str(self.backup_id),
"account_id": self.backup.website.account_id,
}
def backup_archive(account_id, backup_id):
return BACKUP_DIRECTORY / f"account-{account_id}-{backup_id}.zip"
def serve_backup_request():
return serve_apply_request(
REQUEST_VERSION,
AccountBackupRequest.from_manifest,
create_requested_backup,
limit=MAX_MANIFEST_BYTES + 4096,
identity=AccountBackupRequest.identity,
)
def create_requested_backup(request):
import fcntl
if os.geteuid() != 0:
raise ValueError("Run create-request as root on the backup node.")
require_root_directory(BACKUP_DIRECTORY)
directory = os.open(
BACKUP_DIRECTORY, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
)
try:
fcntl.flock(directory, fcntl.LOCK_EX)
ensure_requested_archive(request)
finally:
os.close(directory)
def ensure_requested_archive(request):
archive = backup_archive(
request.backup.website.account_id, request.backup_id
)
if not os.path.lexists(archive):
create_backup(request.backup, archive, DEFAULT_SOCKET)
return
check_root_file(archive, mode=0o600)
try:
with ZipFile(archive) as bundle, bundle.open(MANIFEST_NAME) as source:
existing = read_backup_manifest(source)
except (BadZipFile, KeyError, RuntimeError, ValueError):
raise ValueError(
"An unreadable archive already exists for this request."
) from None
if existing != request.backup:
raise ValueError(
"An archive with a different manifest already exists."
)
+20
View File
@@ -0,0 +1,20 @@
from django.db import transaction
from coulobre.account_backup import AccountBackup
from coulobre.web_node import WebSite
from .resource_requests import lock_hosting_account
def account_backup_manifest(account):
return AccountBackup(
WebSite(account.pk, account.primary_domain),
tuple(database.spec for database in account.databases.all()),
).manifest()
@transaction.atomic
def queue_account_backup(account_id):
account = lock_hosting_account(account_id, customer_id=None)
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
account.backup_jobs.create(manifest=account_backup_manifest(account))
@@ -0,0 +1,64 @@
# Generated by Django 5.2.19 on 2026-11-21 11:25
import uuid
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("hosting", "0019_site_sftp"),
]
operations = [
migrations.CreateModel(
name="AccountBackupJob",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"requested_at",
models.DateTimeField(default=django.utils.timezone.now),
),
(
"last_dispatched_at",
models.DateTimeField(blank=True, null=True),
),
("started_at", models.DateTimeField(blank=True, null=True)),
("finished_at", models.DateTimeField(blank=True, null=True)),
("problem", models.TextField(blank=True)),
(
"backup_id",
models.UUIDField(
default=uuid.uuid4, editable=False, unique=True
),
),
("manifest", models.JSONField()),
(
"account",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="backup_jobs",
to="hosting.hostingaccount",
),
),
],
options={
"indexes": [
models.Index(
fields=["finished_at", "requested_at"],
name="hosting_acc_finishe_d566ad_idx",
)
],
},
),
]
+20
View File
@@ -1,9 +1,12 @@
import uuid
from django.conf import settings from django.conf import settings
from django.core.validators import RegexValidator from django.core.validators import RegexValidator
from django.db import models from django.db import models
from django.urls import reverse from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from coulobre.account_backup_request import backup_archive
from coulobre.database_node import ( from coulobre.database_node import (
DATABASE_SUFFIX_PATTERN, DATABASE_SUFFIX_PATTERN,
INVALID_SUFFIX, INVALID_SUFFIX,
@@ -373,6 +376,23 @@ class DatabaseProvisioning(ProvisioningJob):
) )
class AccountBackupJob(ProvisioningJob):
account = models.ForeignKey(
HostingAccount, on_delete=models.CASCADE, related_name="backup_jobs"
)
backup_id = models.UUIDField(
default=uuid.uuid4, unique=True, editable=False
)
manifest = models.JSONField()
class Meta:
indexes = [models.Index(fields=("finished_at", "requested_at"))]
@property
def archive(self):
return str(backup_archive(self.account_id, self.backup_id))
class DnsPublication(ProvisioningJob): class DnsPublication(ProvisioningJob):
zone = models.OneToOneField( zone = models.OneToOneField(
HostingDnsZone, on_delete=models.CASCADE, related_name="publication" HostingDnsZone, on_delete=models.CASCADE, related_name="publication"
+20 -2
View File
@@ -1,6 +1,11 @@
import json import json
import socket import socket
from coulobre.account_backup_request import (
BACKUP_SOCKET,
BACKUP_TIMEOUT_SECONDS,
)
RESPONSE_LIMIT = 32768 RESPONSE_LIMIT = 32768
@@ -51,15 +56,28 @@ def provision_local_mailbox(mailbox):
) )
def create_local_account_backup(request):
apply_on_local_node(
request,
BACKUP_SOCKET,
"backup node",
"account backup",
identity=request.identity(),
timeout=BACKUP_TIMEOUT_SECONDS + 15,
)
def encode_manifest(manifest): def encode_manifest(manifest):
return json.dumps(manifest).encode("utf-8") return json.dumps(manifest).encode("utf-8")
def apply_on_local_node(spec, socket_path, node, resource, *, identity=None): def apply_on_local_node(
spec, socket_path, node, resource, *, identity=None, timeout=195
):
manifest = spec.manifest() manifest = spec.manifest()
expected = manifest if identity is None else identity expected = manifest if identity is None else identity
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client: with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
client.settimeout(195) client.settimeout(timeout)
client.connect(socket_path) client.connect(socket_path)
client.sendall(encode_manifest(manifest)) client.sendall(encode_manifest(manifest))
client.shutdown(socket.SHUT_WR) client.shutdown(socket.SHUT_WR)
+48 -6
View File
@@ -5,11 +5,17 @@ from django.conf import settings
from django.db.models import Q from django.db.models import Q
from django.utils import timezone from django.utils import timezone
from coulobre.account_backup import AccountBackup
from coulobre.account_backup_request import (
BACKUP_TIMEOUT_SECONDS,
AccountBackupRequest,
)
from coulobre.dns_node import DnsZone from coulobre.dns_node import DnsZone
from coulobre.sftp_keys import SFTPKeys from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebSite from coulobre.web_node import WebSite
from .models import ( from .models import (
AccountBackupJob,
DatabaseProvisioning, DatabaseProvisioning,
DnsPublication, DnsPublication,
MailboxProvisioning, MailboxProvisioning,
@@ -20,6 +26,7 @@ from .models import (
) )
from .node_client import ( from .node_client import (
activate_local_site, activate_local_site,
create_local_account_backup,
enable_local_https, enable_local_https,
provision_local_database, provision_local_database,
provision_local_mailbox, provision_local_mailbox,
@@ -29,6 +36,8 @@ from .node_client import (
from .sftp import site_is_active from .sftp import site_is_active
REDISPATCH_AFTER = timedelta(minutes=5) REDISPATCH_AFTER = timedelta(minutes=5)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups"
WEB_ACTIVATION_QUEUE = "coulobre-web-activation" WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
WEB_HTTPS_QUEUE = "coulobre-web-https" WEB_HTTPS_QUEUE = "coulobre-web-https"
WEB_SFTP_QUEUE = "coulobre-web-sftp" WEB_SFTP_QUEUE = "coulobre-web-sftp"
@@ -118,15 +127,27 @@ def dispatch_mailbox_provisioning():
) )
def dispatch_provisioning_jobs(model, task, queue): @shared_task
stale_before = timezone.now() - REDISPATCH_AFTER def dispatch_account_backups():
if settings.LOCAL_ACCOUNT_BACKUPS:
dispatch_provisioning_jobs(
AccountBackupJob,
create_account_backup,
ACCOUNT_BACKUP_QUEUE,
lease=ACCOUNT_BACKUP_LEASE,
)
def dispatch_provisioning_jobs(model, task, queue, *, lease=REDISPATCH_AFTER):
now = timezone.now()
stale_before = now - REDISPATCH_AFTER
waiting = model.objects.filter(finished_at__isnull=True) waiting = model.objects.filter(finished_at__isnull=True)
pending = ( pending = (
waiting.filter( waiting.filter(
Q(last_dispatched_at__isnull=True) Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before) | Q(last_dispatched_at__lte=stale_before)
) )
.filter(Q(started_at__isnull=True) | Q(started_at__lte=stale_before)) .filter(Q(started_at__isnull=True) | Q(started_at__lte=now - lease))
.order_by("requested_at", "pk") .order_by("requested_at", "pk")
.values_list("pk", "requested_at")[:100] .values_list("pk", "requested_at")[:100]
) )
@@ -257,12 +278,33 @@ def apply_mailbox_provisioning(provisioning):
provision_local_mailbox(provisioning.mailbox.spec) provision_local_mailbox(provisioning.mailbox.spec)
def run_provisioning_job(jobs, job_id, apply, connection_problem): @shared_task(acks_late=True, reject_on_worker_lost=True)
def create_account_backup(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS:
run_provisioning_job(
AccountBackupJob.objects.all(),
job_id,
apply_account_backup,
"Could not complete the request to the local backup node. "
"Check its socket and try again.",
lease=ACCOUNT_BACKUP_LEASE,
)
def apply_account_backup(job):
backup = AccountBackup.from_manifest(job.manifest)
if backup.website.account_id != job.account_id:
raise ValueError("The backup manifest belongs to a different account.")
create_local_account_backup(AccountBackupRequest(job.backup_id, backup))
def run_provisioning_job(
jobs, job_id, apply, connection_problem, *, lease=REDISPATCH_AFTER
):
started_at = timezone.now() started_at = timezone.now()
pending = jobs.filter(pk=job_id, finished_at__isnull=True) pending = jobs.filter(pk=job_id, finished_at__isnull=True)
claim = pending.filter( claim = pending.filter(
Q(started_at__isnull=True) Q(started_at__isnull=True) | Q(started_at__lte=started_at - lease)
| Q(started_at__lte=started_at - REDISPATCH_AFTER)
) )
if not claim.update(started_at=started_at): if not claim.update(started_at=started_at):
return return
@@ -0,0 +1,46 @@
<section class="surface" aria-labelledby="backups-heading">
<header class="section-heading">
<div>
<h2 id="backups-heading">Backups</h2>
<p class="heading-meta">Includes the website and its MariaDB databases.</p>
</div>
{% if not account_backup_pending %}
<form method="post" action="{% url 'panel:account_backup_create' account.pk %}">
{% csrf_token %}
<button class="button primary" type="submit">Create backup</button>
</form>
{% endif %}
</header>
{% if account_backup_jobs %}
<div class="table-scroll">
<table>
<thead>
<tr><th scope="col">Requested</th><th scope="col">Status</th><th scope="col">Archive</th></tr>
</thead>
<tbody>
{% for job in account_backup_jobs %}
<tr>
<td>{{ job.requested_at|date:"j M Y, H:i" }} UTC</td>
<td>
{% if job.state == "configured" %}
Ready
{% else %}
{{ job.state|capfirst }}
{% endif %}
</td>
<td>
{% if job.state == "configured" %}
<code>{{ job.archive }}</code>
{% elif job.problem %}
{{ job.problem }}
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<p class="empty">No backups requested.</p>
{% endif %}
</section>
@@ -34,6 +34,9 @@
{% endif %} {% endif %}
<div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div> <div><dt>Added</dt><dd>{{ account.created_at|date:"j M Y, H:i" }} UTC</dd></div>
</dl> </dl>
{% if show_account_backups %}
{% include "hosting/account_backups.html" %}
{% endif %}
{% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %} {% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
<section class="surface" aria-labelledby="previews-heading"> <section class="surface" aria-labelledby="previews-heading">
<header class="section-heading"> <header class="section-heading">
@@ -0,0 +1,209 @@
import json
from contextlib import redirect_stdout
from datetime import timedelta
from io import BytesIO, StringIO
from pathlib import Path
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from uuid import uuid4
from zipfile import ZipFile
from django.contrib.auth import get_user_model
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from coulobre import account_backup_request
from coulobre.account_backup import AccountBackup, main
from coulobre.account_backup_request import AccountBackupRequest
from coulobre.database_node import DEFAULT_SOCKET
from coulobre.web_node import WebSite
from .models import AccountBackupJob, HostingAccount, HostingDatabase, Reseller
from .tasks import (
ACCOUNT_BACKUP_LEASE,
ACCOUNT_BACKUP_QUEUE,
create_account_backup,
dispatch_account_backups,
)
@override_settings(LOCAL_ACCOUNT_BACKUPS=True)
class PanelAccountBackupTests(TestCase):
@classmethod
def setUpTestData(cls):
users = get_user_model().objects
cls.operator = users.create_superuser("operator")
cls.viewer = users.create_user("reseller")
cls.account = HostingAccount.objects.create(
name="Example account",
primary_domain="example.net",
reseller=Reseller.objects.create(user=cls.viewer),
)
cls.database = HostingDatabase.objects.create(
account=cls.account, suffix="cms"
)
def setUp(self):
self.client.force_login(self.operator)
self.request_url = reverse(
"panel:account_backup_create", args=[self.account.pk]
)
def test_duplicate_requests_keep_one_queued_backup_with_the_original_plan(
self,
):
self.assertContains(
self.client.get(self.account.get_absolute_url()), "Create backup"
)
self.assertRedirects(
self.client.post(self.request_url), self.account.get_absolute_url()
)
HostingDatabase.objects.create(account=self.account, suffix="shop")
self.client.post(self.request_url)
job = AccountBackupJob.objects.get(account=self.account)
manifest = AccountBackup.from_manifest(job.manifest)
self.assertEqual(manifest.databases, (self.database.spec,))
page = self.client.get(self.account.get_absolute_url())
self.assertContains(page, "Queued")
self.assertNotContains(page, "Create backup")
def test_worker_reports_the_archive_and_allows_another_backup(self):
self.client.post(self.request_url)
job = AccountBackupJob.objects.get(account=self.account)
with patch(
"coulobre.hosting.tasks.create_local_account_backup"
) as node:
create_account_backup(job.pk)
create_account_backup(job.pk)
node.assert_called_once_with(
AccountBackupRequest(
job.backup_id, AccountBackup.from_manifest(job.manifest)
)
)
page = self.client.get(self.account.get_absolute_url())
self.assertContains(page, "Ready")
self.assertContains(page, job.archive)
self.client.post(self.request_url)
self.assertEqual(self.account.backup_jobs.count(), 2)
def test_a_running_backup_is_only_reclaimed_after_its_own_lease(self):
self.client.post(self.request_url)
job = AccountBackupJob.objects.get(account=self.account)
job.started_at = job.last_dispatched_at = timezone.now() - timedelta(
minutes=6
)
job.save(update_fields=["started_at", "last_dispatched_at"])
with (
patch.object(create_account_backup, "apply_async") as publish,
patch(
"coulobre.hosting.tasks.create_local_account_backup"
) as node,
):
dispatch_account_backups()
create_account_backup(job.pk)
publish.assert_not_called()
node.assert_not_called()
job.started_at = timezone.now() - ACCOUNT_BACKUP_LEASE
job.save(update_fields=["started_at"])
dispatch_account_backups()
create_account_backup(job.pk)
publish.assert_called_once_with(
args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False
)
self.assertEqual(node.call_args.args[0].backup_id, job.backup_id)
@override_settings(LOCAL_ACCOUNT_BACKUPS=False)
def test_disabled_panel_backup_has_no_action(self):
self.assertEqual(self.client.post(self.request_url).status_code, 404)
self.assertNotContains(
self.client.get(self.account.get_absolute_url()), "Create backup"
)
self.assertFalse(AccountBackupJob.objects.exists())
def test_reseller_cannot_create_or_view_backup_jobs(self):
self.client.force_login(self.viewer)
self.assertEqual(self.client.post(self.request_url).status_code, 403)
self.assertNotContains(
self.client.get(self.account.get_absolute_url()), "Create backup"
)
self.assertFalse(AccountBackupJob.objects.exists())
class AccountBackupRequestTests(SimpleTestCase):
def setUp(self):
self.directory = Path(self.enterContext(TemporaryDirectory()))
self.backup = AccountBackup(WebSite(123, "example.net"), ())
self.request = AccountBackupRequest(uuid4(), self.backup)
self.enterContext(
patch.object(
account_backup_request, "BACKUP_DIRECTORY", self.directory
)
)
self.enterContext(
patch.object(account_backup_request, "require_root_directory")
)
self.enterContext(
patch.object(account_backup_request, "check_root_file")
)
self.enterContext(
patch.object(account_backup_request.os, "geteuid", return_value=0)
)
self.create = self.enterContext(
patch.object(
account_backup_request,
"create_backup",
side_effect=self.write_zip,
)
)
def write_zip(self, backup, archive, socket):
with ZipFile(archive, mode="x") as bundle:
bundle.writestr("manifest.json", json.dumps(backup.manifest()))
def send(self, manifest):
source = BytesIO(json.dumps(manifest).encode())
with (
patch("sys.stdin", SimpleNamespace(buffer=source)),
redirect_stdout(StringIO()) as output,
):
result = main(["create-request"])
return result, json.loads(output.getvalue())
def test_replayed_request_reuses_the_published_archive(self):
archive = self.directory / f"account-123-{self.request.backup_id}.zip"
for _ in range(2):
code, report = self.send(self.request.manifest())
self.assertEqual(code, 0)
self.assertEqual(
report,
self.request.identity()
| {"state": "configured", "problem": None},
)
self.create.assert_called_once_with(
self.backup, archive, DEFAULT_SOCKET
)
def test_request_does_not_accept_a_destination_path(self):
code, report = self.send(
self.request.manifest() | {"archive": str(self.directory)}
)
self.assertEqual(code, 1)
self.assertEqual(report["state"], "failed")
self.create.assert_not_called()
def test_replay_rejects_an_archive_with_a_different_plan(self):
archive = self.directory / f"account-123-{self.request.backup_id}.zip"
self.write_zip(
AccountBackup(WebSite(123, "other.example"), ()), archive, None
)
code, report = self.send(self.request.manifest())
self.assertEqual(code, 1)
self.assertIn("a different manifest", report["problem"])
self.create.assert_not_called()
+5
View File
@@ -25,6 +25,11 @@ urlpatterns = [
views.DownloadAccountBackupManifest.as_view(), views.DownloadAccountBackupManifest.as_view(),
name="account_backup_manifest", name="account_backup_manifest",
), ),
path(
"accounts/<int:pk>/backups/",
views.RequestAccountBackup.as_view(),
name="account_backup_create",
),
path( path(
"accounts/<int:pk>/sftp/", "accounts/<int:pk>/sftp/",
views.SiteSFTPKeys.as_view(), views.SiteSFTPKeys.as_view(),
+32 -7
View File
@@ -26,11 +26,9 @@ from django.views.generic import (
) )
from django.views.generic.detail import SingleObjectMixin from django.views.generic.detail import SingleObjectMixin
from coulobre.account_backup import AccountBackup
from coulobre.dns_node import MAX_SOA_SERIAL from coulobre.dns_node import MAX_SOA_SERIAL
from coulobre.mail_node import INVALID_LOCAL_PART from coulobre.mail_node import INVALID_LOCAL_PART
from coulobre.sftp_keys import public_key_fingerprint from coulobre.sftp_keys import public_key_fingerprint
from coulobre.web_node import WebSite
from .access import ( from .access import (
OperatorOnlyMixin, OperatorOnlyMixin,
@@ -39,6 +37,7 @@ from .access import (
is_tenant, is_tenant,
reseller_for_user, reseller_for_user,
) )
from .account_backups import account_backup_manifest, queue_account_backup
from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record from .dns_forms import DnsZoneEditForm, DnsZoneForm, format_txt_record
from .dns_publication import queue_dns_publication from .dns_publication import queue_dns_publication
from .impersonation import ( from .impersonation import (
@@ -81,6 +80,10 @@ VIEW_DATABASES = "hosting.view_hostingdatabase"
VIEW_DNS_ZONES = "hosting.view_hostingdnszone" VIEW_DNS_ZONES = "hosting.view_hostingdnszone"
VIEW_MAILBOXES = "hosting.view_hostingmailbox" VIEW_MAILBOXES = "hosting.view_hostingmailbox"
EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES) EXPORT_BACKUP_MANIFEST = (VIEW_ACCOUNTS, VIEW_PLANS, VIEW_DATABASES)
MANAGE_ACCOUNT_BACKUPS = (
*EXPORT_BACKUP_MANIFEST,
"hosting.add_accountbackupjob",
)
ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation") ACTIVATE_WEB = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webactivation")
ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps") ENABLE_WEB_HTTPS = (VIEW_ACCOUNTS, VIEW_PLANS, "hosting.add_webhttps")
PROVISION_DATABASE = ( PROVISION_DATABASE = (
@@ -235,6 +238,19 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
context["export_backup_manifest"] = not tenant and user.has_perms( context["export_backup_manifest"] = not tenant and user.has_perms(
EXPORT_BACKUP_MANIFEST EXPORT_BACKUP_MANIFEST
) )
if (
settings.LOCAL_ACCOUNT_BACKUPS
and not tenant
and user.has_perms(MANAGE_ACCOUNT_BACKUPS)
):
jobs = list(
self.object.backup_jobs.order_by("-requested_at", "-pk")[:10]
)
context["show_account_backups"] = True
context["account_backup_jobs"] = jobs
context["account_backup_pending"] = any(
job.finished_at is None for job in jobs
)
context["manage_sftp"] = ( context["manage_sftp"] = (
settings.LOCAL_WEB_SFTP settings.LOCAL_WEB_SFTP
and can_manage_sftp(user) and can_manage_sftp(user)
@@ -289,12 +305,8 @@ class DownloadAccountBackupManifest(
def get(self, request, pk): def get(self, request, pk):
account = get_object_or_404(HostingAccount, pk=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( return JsonResponse(
backup.manifest(), account_backup_manifest(account),
headers={ headers={
"Cache-Control": "private, no-store", "Cache-Control": "private, no-store",
"Content-Disposition": ( "Content-Disposition": (
@@ -305,6 +317,19 @@ class DownloadAccountBackupManifest(
) )
class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
permission_required = MANAGE_ACCOUNT_BACKUPS
def post(self, request, pk):
if not settings.LOCAL_ACCOUNT_BACKUPS:
raise Http404
try:
queue_account_backup(pk)
except HostingAccount.DoesNotExist:
raise Http404 from None
return redirect("panel:account", pk=pk)
class SiteSFTPKeys(PermissionRequiredMixin, FormView): class SiteSFTPKeys(PermissionRequiredMixin, FormView):
form_class = SFTPKeyUploadForm form_class = SFTPKeyUploadForm
template_name = "hosting/sftp_keys.html" template_name = "hosting/sftp_keys.html"
+7
View File
@@ -128,6 +128,7 @@ LOCAL_DNS_PUBLISHING = os.environ.get("COULOBRE_LOCAL_DNS_PUBLISHING") == "1"
LOCAL_MAILBOX_PROVISIONING = ( LOCAL_MAILBOX_PROVISIONING = (
os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") == "1" os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") == "1"
) )
LOCAL_ACCOUNT_BACKUPS = os.environ.get("COULOBRE_LOCAL_ACCOUNT_BACKUPS") == "1"
CELERY_BEAT_SCHEDULE = { CELERY_BEAT_SCHEDULE = {
"dispatch-web-provisioning-plans": { "dispatch-web-provisioning-plans": {
"task": "coulobre.hosting.tasks.dispatch_web_plans", "task": "coulobre.hosting.tasks.dispatch_web_plans",
@@ -171,3 +172,9 @@ if LOCAL_MAILBOX_PROVISIONING:
"schedule": 5.0, "schedule": 5.0,
"options": {"expires": 4.0}, "options": {"expires": 4.0},
} }
if LOCAL_ACCOUNT_BACKUPS:
CELERY_BEAT_SCHEDULE["dispatch-account-backups"] = {
"task": "coulobre.hosting.tasks.dispatch_account_backups",
"schedule": 5.0,
"options": {"expires": 4.0},
}