Schedule daily and weekly account backups #34
No files matched your search
+21
-2
@@ -405,6 +405,21 @@ Archives are stored under `/var/lib/coulobre/account-backups/` with root-only
|
|||||||
access. Retrieve archives and manage their retention on the server. Recovery
|
access. Retrieve archives and manage their retention on the server. Recovery
|
||||||
uses the existing [account bundle commands](development.md#recover-backups-from-the-bundle).
|
uses the existing [account bundle commands](development.md#recover-backups-from-the-bundle).
|
||||||
|
|
||||||
|
#### Schedule backups for an account
|
||||||
|
|
||||||
|
Select **Schedule backups** on the account page. Choose a daily time or a
|
||||||
|
weekly day and time, all in UTC. To pause the schedule, clear
|
||||||
|
**Enable scheduled backups** and save. The account page shows the next
|
||||||
|
scheduled run and identifies the source of each backup in the history.
|
||||||
|
Operators also need **Can change account backup schedule** to manage schedules.
|
||||||
|
|
||||||
|
The scheduler captures the account's current resources when it queues the
|
||||||
|
backup. If an account already has a backup queued or running at dispatch,
|
||||||
|
the scheduler skips that occurrence. After a period offline, it queues at
|
||||||
|
most one missed backup per account and continues with the next future time.
|
||||||
|
Scheduled ZIPs are stored alongside manual backups and require the same
|
||||||
|
server-side retention management.
|
||||||
|
|
||||||
#### Include mailboxes on the same server
|
#### Include mailboxes on the same server
|
||||||
|
|
||||||
Complete the [Postfix and Dovecot setup](development.md#apply-a-mailbox-manifest)
|
Complete the [Postfix and Dovecot setup](development.md#apply-a-mailbox-manifest)
|
||||||
@@ -420,8 +435,12 @@ sudo systemctl daemon-reload
|
|||||||
Set `COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1` in `/etc/coulobre/panel.env` and
|
Set `COULOBRE_LOCAL_ACCOUNT_BACKUP_MAIL=1` in `/etc/coulobre/panel.env` and
|
||||||
restart `coulobre-panel` and `coulobre-backup-worker`. Operators with
|
restart `coulobre-panel` and `coulobre-backup-worker`. Operators with
|
||||||
permission to view mailbox requests can select **Include mailboxes** when
|
permission to view mailbox requests can select **Include mailboxes** when
|
||||||
creating an account backup. Provision all listed mailboxes before requesting
|
starting or scheduling an account backup. They can also edit an existing
|
||||||
a backup with mail. For mailboxes on a separate server, use the
|
schedule that includes mail. If you disable mailbox backups while such a
|
||||||
|
schedule is enabled, the subsequent jobs report a failure until you adjust
|
||||||
|
the schedule or re-enable local mailbox backups. Provision all listed
|
||||||
|
mailboxes before requesting a backup with mail. For mailboxes on a separate
|
||||||
|
server, use the
|
||||||
[bundle workflow for separate nodes](development.md#bundle-backups-from-separate-nodes).
|
[bundle workflow for separate nodes](development.md#bundle-backups-from-separate-nodes).
|
||||||
|
|
||||||
## Publish local DNS zones from the panel
|
## Publish local DNS zones from the panel
|
||||||
|
|||||||
+6
-4
@@ -1030,10 +1030,12 @@ each listed database, and the requested mailbox archives. Back up DNS and panel
|
|||||||
settings separately.
|
settings separately.
|
||||||
|
|
||||||
On a single-server installation, operators can start a backup of the website
|
On a single-server installation, operators can start a backup of the website
|
||||||
and databases directly from the account page and view its status there. If
|
and databases directly from the account page and view its status there. The
|
||||||
mail is hosted on that server too, enable the **Include mailboxes** option.
|
panel can also run one daily or weekly backup schedule per account. If mail
|
||||||
[Enable account backups in the panel](deployment.md#start-local-account-backups-from-the-panel),
|
is hosted on that server too, enable the **Include mailboxes** option.
|
||||||
[include local mailboxes](deployment.md#include-mailboxes-on-the-same-server)
|
See [local account backups](deployment.md#start-local-account-backups-from-the-panel),
|
||||||
|
[backup schedules](deployment.md#schedule-backups-for-an-account), and
|
||||||
|
[local mailbox backups](deployment.md#include-mailboxes-on-the-same-server).
|
||||||
|
|
||||||
If all resources in the manifest are on one server, run the account backup
|
If all resources in the manifest are on one server, run the account backup
|
||||||
command there as root. To include mail, pass the manifest downloaded with
|
command there as root. To include mail, pass the manifest downloaded with
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
from django import forms
|
||||||
|
|
||||||
|
from .models import AccountBackupSchedule
|
||||||
|
|
||||||
|
SCHEDULE_FIELDS = (
|
||||||
|
"enabled",
|
||||||
|
"frequency",
|
||||||
|
"weekday",
|
||||||
|
"time",
|
||||||
|
"include_mailboxes",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountBackupScheduleForm(forms.Form):
|
||||||
|
enabled = forms.BooleanField(
|
||||||
|
label="Enable scheduled backups", required=False
|
||||||
|
)
|
||||||
|
frequency = forms.ChoiceField(
|
||||||
|
choices=AccountBackupSchedule.Frequency.choices
|
||||||
|
)
|
||||||
|
weekday = forms.TypedChoiceField(
|
||||||
|
choices=[("", "Select a day"), *AccountBackupSchedule.Weekday.choices],
|
||||||
|
coerce=int,
|
||||||
|
empty_value=None,
|
||||||
|
required=False,
|
||||||
|
help_text="Required for weekly backups.",
|
||||||
|
)
|
||||||
|
time = forms.TimeField(
|
||||||
|
label="Time (UTC)",
|
||||||
|
input_formats=["%H:%M"],
|
||||||
|
widget=forms.TimeInput(format="%H:%M", attrs={"type": "time"}),
|
||||||
|
)
|
||||||
|
include_mailboxes = forms.BooleanField(required=False)
|
||||||
|
|
||||||
|
def __init__(self, *args, allow_mail, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.allow_mail = allow_mail
|
||||||
|
if not allow_mail and not self.initial.get("include_mailboxes"):
|
||||||
|
del self.fields["include_mailboxes"]
|
||||||
|
|
||||||
|
def clean(self):
|
||||||
|
cleaned = super().clean()
|
||||||
|
if cleaned.get("frequency") == AccountBackupSchedule.Frequency.WEEKLY:
|
||||||
|
if "weekday" in cleaned and cleaned["weekday"] is None:
|
||||||
|
self.add_error("weekday", "Select a day for weekly backups.")
|
||||||
|
else:
|
||||||
|
cleaned["weekday"] = None
|
||||||
|
|
||||||
|
cleaned.setdefault("include_mailboxes", False)
|
||||||
|
if (
|
||||||
|
cleaned.get("enabled")
|
||||||
|
and cleaned["include_mailboxes"]
|
||||||
|
and not self.allow_mail
|
||||||
|
):
|
||||||
|
self.add_error(
|
||||||
|
"include_mailboxes",
|
||||||
|
"Enable local mailbox backups, clear this option, "
|
||||||
|
"or pause the schedule.",
|
||||||
|
)
|
||||||
|
return cleaned
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
|
||||||
|
from django.core.exceptions import PermissionDenied
|
||||||
from django.db import transaction
|
from django.db import transaction
|
||||||
|
from django.utils import timezone
|
||||||
|
|
||||||
from coulobre.account_backup import AccountBackup
|
from coulobre.account_backup import AccountBackup
|
||||||
from coulobre.web_node import WebSite
|
from coulobre.web_node import WebSite
|
||||||
|
|
||||||
from .models import HostingMailbox
|
from .models import AccountBackupSchedule, HostingAccount, HostingMailbox
|
||||||
from .resource_requests import lock_hosting_account
|
from .resource_requests import lock_hosting_account
|
||||||
|
|
||||||
|
|
||||||
@@ -24,9 +28,85 @@ def account_backup_manifest(account, *, include_mailboxes=False):
|
|||||||
@transaction.atomic
|
@transaction.atomic
|
||||||
def queue_account_backup(account_id, *, include_mailboxes=False):
|
def queue_account_backup(account_id, *, include_mailboxes=False):
|
||||||
account = lock_hosting_account(account_id, customer_id=None)
|
account = lock_hosting_account(account_id, customer_id=None)
|
||||||
|
_enqueue_backup(account, include_mailboxes=include_mailboxes)
|
||||||
|
|
||||||
|
|
||||||
|
def _enqueue_backup(account, *, include_mailboxes, scheduled_for=None):
|
||||||
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
|
if not account.backup_jobs.filter(finished_at__isnull=True).exists():
|
||||||
account.backup_jobs.create(
|
account.backup_jobs.create(
|
||||||
manifest=account_backup_manifest(
|
manifest=account_backup_manifest(
|
||||||
account, include_mailboxes=include_mailboxes
|
account, include_mailboxes=include_mailboxes
|
||||||
)
|
),
|
||||||
|
scheduled_for=scheduled_for,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _next_backup_run(schedule, now):
|
||||||
|
now = now.astimezone(UTC)
|
||||||
|
run_at = datetime.combine(now.date(), schedule.time, tzinfo=UTC)
|
||||||
|
if schedule.frequency == AccountBackupSchedule.Frequency.WEEKLY:
|
||||||
|
run_at += timedelta(days=(schedule.weekday - now.weekday()) % 7)
|
||||||
|
interval = timedelta(weeks=1)
|
||||||
|
else:
|
||||||
|
interval = timedelta(days=1)
|
||||||
|
return run_at if run_at > now else run_at + interval
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def save_backup_schedule(account_id, *, can_manage_mail, schedule_fields):
|
||||||
|
account = lock_hosting_account(account_id, customer_id=None)
|
||||||
|
schedule = getattr(account, "backup_schedule", None)
|
||||||
|
if schedule is None:
|
||||||
|
schedule = AccountBackupSchedule(account=account)
|
||||||
|
if not can_manage_mail and (
|
||||||
|
schedule.include_mailboxes or schedule_fields["include_mailboxes"]
|
||||||
|
):
|
||||||
|
raise PermissionDenied
|
||||||
|
|
||||||
|
timing_changed = any(
|
||||||
|
getattr(schedule, field) != schedule_fields[field]
|
||||||
|
for field in ("enabled", "frequency", "weekday", "time")
|
||||||
|
)
|
||||||
|
for field, value in schedule_fields.items():
|
||||||
|
setattr(schedule, field, value)
|
||||||
|
if not schedule.enabled:
|
||||||
|
schedule.next_run_at = None
|
||||||
|
elif timing_changed or schedule.next_run_at is None:
|
||||||
|
schedule.next_run_at = _next_backup_run(schedule, timezone.now())
|
||||||
|
schedule.save()
|
||||||
|
|
||||||
|
|
||||||
|
def queue_due_account_backups(now):
|
||||||
|
due_account_ids = list(
|
||||||
|
AccountBackupSchedule.objects.filter(
|
||||||
|
enabled=True, next_run_at__lte=now
|
||||||
|
)
|
||||||
|
.order_by("next_run_at", "pk")
|
||||||
|
.values_list("account_id", flat=True)[:100]
|
||||||
|
)
|
||||||
|
for account_id in due_account_ids:
|
||||||
|
try:
|
||||||
|
_queue_scheduled_backup(account_id, now)
|
||||||
|
except HostingAccount.DoesNotExist:
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def _queue_scheduled_backup(account_id, now):
|
||||||
|
account = lock_hosting_account(account_id, customer_id=None)
|
||||||
|
schedule = getattr(account, "backup_schedule", None)
|
||||||
|
if (
|
||||||
|
schedule is None
|
||||||
|
or not schedule.enabled
|
||||||
|
or schedule.next_run_at is None
|
||||||
|
or schedule.next_run_at > now
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
_enqueue_backup(
|
||||||
|
account,
|
||||||
|
include_mailboxes=schedule.include_mailboxes,
|
||||||
|
scheduled_for=schedule.next_run_at,
|
||||||
|
)
|
||||||
|
schedule.next_run_at = _next_backup_run(schedule, now)
|
||||||
|
schedule.save(update_fields=["next_run_at"])
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-11-21 13:22
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0024_website_storage_limits"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name="accountbackupjob",
|
||||||
|
name="scheduled_for",
|
||||||
|
field=models.DateTimeField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="AccountBackupSchedule",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("enabled", models.BooleanField(default=True)),
|
||||||
|
(
|
||||||
|
"frequency",
|
||||||
|
models.CharField(
|
||||||
|
choices=[("daily", "Daily"), ("weekly", "Weekly")],
|
||||||
|
default="daily",
|
||||||
|
max_length=6,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"weekday",
|
||||||
|
models.PositiveSmallIntegerField(
|
||||||
|
blank=True,
|
||||||
|
choices=[
|
||||||
|
(0, "Monday"),
|
||||||
|
(1, "Tuesday"),
|
||||||
|
(2, "Wednesday"),
|
||||||
|
(3, "Thursday"),
|
||||||
|
(4, "Friday"),
|
||||||
|
(5, "Saturday"),
|
||||||
|
(6, "Sunday"),
|
||||||
|
],
|
||||||
|
null=True,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
("time", models.TimeField(verbose_name="time (UTC)")),
|
||||||
|
("include_mailboxes", models.BooleanField(default=False)),
|
||||||
|
("next_run_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
(
|
||||||
|
"account",
|
||||||
|
models.OneToOneField(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
related_name="backup_schedule",
|
||||||
|
to="hosting.hostingaccount",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"indexes": [
|
||||||
|
models.Index(
|
||||||
|
fields=["enabled", "next_run_at"],
|
||||||
|
name="hosting_acc_enabled_34d512_idx",
|
||||||
|
)
|
||||||
|
],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -445,6 +445,7 @@ class AccountBackupJob(ProvisioningJob):
|
|||||||
default=uuid.uuid4, unique=True, editable=False
|
default=uuid.uuid4, unique=True, editable=False
|
||||||
)
|
)
|
||||||
manifest = models.JSONField()
|
manifest = models.JSONField()
|
||||||
|
scheduled_for = models.DateTimeField(null=True, blank=True)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
indexes = [models.Index(fields=("finished_at", "requested_at"))]
|
||||||
@@ -458,6 +459,40 @@ class AccountBackupJob(ProvisioningJob):
|
|||||||
return "mailboxes" in self.manifest
|
return "mailboxes" in self.manifest
|
||||||
|
|
||||||
|
|
||||||
|
class AccountBackupSchedule(models.Model):
|
||||||
|
class Frequency(models.TextChoices):
|
||||||
|
DAILY = "daily", "Daily"
|
||||||
|
WEEKLY = "weekly", "Weekly"
|
||||||
|
|
||||||
|
class Weekday(models.IntegerChoices):
|
||||||
|
MONDAY = 0, "Monday"
|
||||||
|
TUESDAY = 1, "Tuesday"
|
||||||
|
WEDNESDAY = 2, "Wednesday"
|
||||||
|
THURSDAY = 3, "Thursday"
|
||||||
|
FRIDAY = 4, "Friday"
|
||||||
|
SATURDAY = 5, "Saturday"
|
||||||
|
SUNDAY = 6, "Sunday"
|
||||||
|
|
||||||
|
account = models.OneToOneField(
|
||||||
|
HostingAccount,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="backup_schedule",
|
||||||
|
)
|
||||||
|
enabled = models.BooleanField(default=True)
|
||||||
|
frequency = models.CharField(
|
||||||
|
max_length=6, choices=Frequency, default=Frequency.DAILY
|
||||||
|
)
|
||||||
|
weekday = models.PositiveSmallIntegerField(
|
||||||
|
choices=Weekday, null=True, blank=True
|
||||||
|
)
|
||||||
|
time = models.TimeField("time (UTC)")
|
||||||
|
include_mailboxes = models.BooleanField(default=False)
|
||||||
|
next_run_at = models.DateTimeField(null=True, blank=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
indexes = [models.Index(fields=("enabled", "next_run_at"))]
|
||||||
|
|
||||||
|
|
||||||
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"
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ 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 .account_backups import queue_due_account_backups
|
||||||
from .models import (
|
from .models import (
|
||||||
AccountBackupJob,
|
AccountBackupJob,
|
||||||
DatabaseProvisioning,
|
DatabaseProvisioning,
|
||||||
@@ -151,6 +152,7 @@ def dispatch_mailbox_provisioning():
|
|||||||
@shared_task
|
@shared_task
|
||||||
def dispatch_account_backups():
|
def dispatch_account_backups():
|
||||||
if settings.LOCAL_ACCOUNT_BACKUPS:
|
if settings.LOCAL_ACCOUNT_BACKUPS:
|
||||||
|
queue_due_account_backups(timezone.now())
|
||||||
dispatch_provisioning_jobs(
|
dispatch_provisioning_jobs(
|
||||||
AccountBackupJob,
|
AccountBackupJob,
|
||||||
create_account_backup,
|
create_account_backup,
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{% extends "hosting/base.html" %}
|
||||||
|
{% block title %}Backup schedule · Coulobre Panel{% endblock %}
|
||||||
|
{% block content %}
|
||||||
|
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||||
|
<header class="page-heading">
|
||||||
|
<div>
|
||||||
|
<h1>Backup schedule</h1>
|
||||||
|
<p class="heading-meta domain">{{ account.primary_domain }}</p>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
<form method="post" class="editor">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ form.as_div }}
|
||||||
|
<div class="form-actions">
|
||||||
|
<button class="button primary" type="submit">Save backup schedule</button>
|
||||||
|
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@@ -3,6 +3,18 @@
|
|||||||
<div>
|
<div>
|
||||||
<h2 id="backups-heading">Backups</h2>
|
<h2 id="backups-heading">Backups</h2>
|
||||||
<p class="heading-meta">Includes the website and its MariaDB databases.</p>
|
<p class="heading-meta">Includes the website and its MariaDB databases.</p>
|
||||||
|
{% if account_backup_schedule %}
|
||||||
|
<p class="heading-meta">
|
||||||
|
{{ account_backup_schedule.get_frequency_display }}
|
||||||
|
{% if account_backup_schedule.weekday is not None %}on {{ account_backup_schedule.get_weekday_display }}{% endif %}
|
||||||
|
at {{ account_backup_schedule.time|time:"H:i" }} UTC{% if account_backup_schedule.include_mailboxes %}, including mailboxes{% endif %}.
|
||||||
|
{% if account_backup_schedule.enabled %}
|
||||||
|
Next run {{ account_backup_schedule.next_run_at|date:"j M Y, H:i" }} UTC.
|
||||||
|
{% else %}
|
||||||
|
Schedule paused.
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% if not account_backup_pending %}
|
{% if not account_backup_pending %}
|
||||||
<form class="form-actions" method="post" action="{% url 'panel:account_backup_create' account.pk %}">
|
<form class="form-actions" method="post" action="{% url 'panel:account_backup_create' account.pk %}">
|
||||||
@@ -14,6 +26,11 @@
|
|||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</header>
|
</header>
|
||||||
|
{% if edit_account_backup_schedule %}
|
||||||
|
<div class="form-actions">
|
||||||
|
<a class="button secondary" href="{% url 'panel:account_backup_schedule' account.pk %}">{% if account_backup_schedule %}Edit backup schedule{% else %}Schedule backups{% endif %}</a>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
{% if account_backup_pending_hidden %}
|
{% if account_backup_pending_hidden %}
|
||||||
<p class="empty">A backup is already queued or running.</p>
|
<p class="empty">A backup is already queued or running.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -21,12 +38,19 @@
|
|||||||
<div class="table-scroll">
|
<div class="table-scroll">
|
||||||
<table>
|
<table>
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th scope="col">Requested</th><th scope="col">Contents</th><th scope="col">Status</th><th scope="col">Archive</th></tr>
|
<tr><th scope="col">Requested</th><th scope="col">Source</th><th scope="col">Contents</th><th scope="col">Status</th><th scope="col">Archive</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for job in account_backup_jobs %}
|
{% for job in account_backup_jobs %}
|
||||||
<tr>
|
<tr>
|
||||||
<td>{{ job.requested_at|date:"j M Y, H:i" }} UTC</td>
|
<td>{{ job.requested_at|date:"j M Y, H:i" }} UTC</td>
|
||||||
|
<td>
|
||||||
|
{% if job.scheduled_for %}
|
||||||
|
Scheduled <time datetime="{{ job.scheduled_for|date:"c" }}">{{ job.scheduled_for|date:"j M Y, H:i" }} UTC</time>
|
||||||
|
{% else %}
|
||||||
|
Manual
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
<td>{% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %}</td>
|
<td>{% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %}</td>
|
||||||
<td>
|
<td>
|
||||||
{% if job.state == "configured" %}
|
{% if job.state == "configured" %}
|
||||||
|
|||||||
@@ -0,0 +1,279 @@
|
|||||||
|
from datetime import UTC, datetime, timedelta, timezone
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.contrib.auth.models import Permission
|
||||||
|
from django.test import TestCase, override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from coulobre.account_backup import AccountBackup
|
||||||
|
|
||||||
|
from .account_backups import queue_due_account_backups
|
||||||
|
from .models import (
|
||||||
|
AccountBackupSchedule,
|
||||||
|
HostingAccount,
|
||||||
|
HostingDatabase,
|
||||||
|
HostingMailbox,
|
||||||
|
HostingMailDomain,
|
||||||
|
Reseller,
|
||||||
|
)
|
||||||
|
from .tasks import (
|
||||||
|
ACCOUNT_BACKUP_QUEUE,
|
||||||
|
create_account_backup,
|
||||||
|
dispatch_account_backups,
|
||||||
|
)
|
||||||
|
|
||||||
|
MONDAY = datetime(2030, 7, 1, 2, 30, tzinfo=UTC)
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(LOCAL_ACCOUNT_BACKUPS=True, LOCAL_ACCOUNT_BACKUP_MAIL=False)
|
||||||
|
class AccountBackupScheduleTests(TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpTestData(cls):
|
||||||
|
cls.operator = get_user_model().objects.create_superuser("operator")
|
||||||
|
cls.account = HostingAccount.objects.create(
|
||||||
|
name="Example account", primary_domain="example.net"
|
||||||
|
)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.client.force_login(self.operator)
|
||||||
|
self.url = reverse(
|
||||||
|
"panel:account_backup_schedule", args=[self.account.pk]
|
||||||
|
)
|
||||||
|
|
||||||
|
def save_schedule(self, **overrides):
|
||||||
|
data = {"enabled": "on", "frequency": "daily", "time": "02:30"}
|
||||||
|
return self.client.post(self.url, data | overrides)
|
||||||
|
|
||||||
|
def make_due(self, **fields):
|
||||||
|
defaults = {"time": MONDAY.time(), "next_run_at": MONDAY}
|
||||||
|
return AccountBackupSchedule.objects.create(
|
||||||
|
account=self.account, **(defaults | fields)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_daily_schedule_can_be_saved_paused_and_resumed(self):
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()),
|
||||||
|
"Schedule backups",
|
||||||
|
)
|
||||||
|
self.assertNotContains(self.client.get(self.url), "Include mailboxes")
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.account_backups.timezone", now=lambda: MONDAY
|
||||||
|
):
|
||||||
|
self.assertRedirects(
|
||||||
|
self.save_schedule(), self.account.get_absolute_url()
|
||||||
|
)
|
||||||
|
schedule = AccountBackupSchedule.objects.get(account=self.account)
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=1))
|
||||||
|
page = self.client.get(self.account.get_absolute_url())
|
||||||
|
self.assertContains(page, "Next run 2 Jul 2030, 02:30 UTC")
|
||||||
|
self.assertContains(page, "Edit backup schedule")
|
||||||
|
|
||||||
|
self.save_schedule(enabled="")
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertFalse(schedule.enabled)
|
||||||
|
self.assertIsNone(schedule.next_run_at)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()), "Schedule paused"
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.account_backups.timezone",
|
||||||
|
now=lambda: MONDAY + timedelta(days=2),
|
||||||
|
):
|
||||||
|
self.save_schedule()
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=3))
|
||||||
|
|
||||||
|
def test_weekly_schedule_requires_a_day_and_uses_utc(self):
|
||||||
|
response = self.save_schedule(frequency="weekly")
|
||||||
|
self.assertContains(response, "Select a day for weekly backups.")
|
||||||
|
self.assertFalse(AccountBackupSchedule.objects.exists())
|
||||||
|
now = (MONDAY - timedelta(minutes=1)).astimezone(
|
||||||
|
timezone(-timedelta(hours=4))
|
||||||
|
)
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.account_backups.timezone", now=lambda: now
|
||||||
|
):
|
||||||
|
self.assertEqual(
|
||||||
|
self.save_schedule(
|
||||||
|
frequency="weekly", weekday="0"
|
||||||
|
).status_code,
|
||||||
|
302,
|
||||||
|
)
|
||||||
|
schedule = AccountBackupSchedule.objects.get(account=self.account)
|
||||||
|
self.assertEqual(
|
||||||
|
schedule.weekday, AccountBackupSchedule.Weekday.MONDAY
|
||||||
|
)
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY)
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()), "on Monday"
|
||||||
|
)
|
||||||
|
|
||||||
|
queue_due_account_backups(MONDAY)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY + timedelta(weeks=1))
|
||||||
|
|
||||||
|
def test_saving_an_unchanged_schedule_keeps_a_due_occurrence(self):
|
||||||
|
schedule = self.make_due()
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.account_backups.timezone", now=lambda: MONDAY
|
||||||
|
):
|
||||||
|
self.assertEqual(self.save_schedule().status_code, 302)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY)
|
||||||
|
|
||||||
|
def test_dispatch_catches_up_once_and_uses_the_current_account_manifest(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
schedule = self.make_due()
|
||||||
|
database = HostingDatabase.objects.create(
|
||||||
|
account=self.account, suffix="cms"
|
||||||
|
)
|
||||||
|
now = MONDAY + timedelta(days=4, hours=1)
|
||||||
|
with (
|
||||||
|
patch("django.utils.timezone.now", return_value=now),
|
||||||
|
patch.object(create_account_backup, "apply_async") as publish,
|
||||||
|
):
|
||||||
|
dispatch_account_backups()
|
||||||
|
dispatch_account_backups()
|
||||||
|
|
||||||
|
job = self.account.backup_jobs.get()
|
||||||
|
self.assertEqual(job.scheduled_for, MONDAY)
|
||||||
|
self.assertEqual(
|
||||||
|
AccountBackup.from_manifest(job.manifest).databases,
|
||||||
|
(database.spec,),
|
||||||
|
)
|
||||||
|
publish.assert_called_once_with(
|
||||||
|
args=[job.pk], queue=ACCOUNT_BACKUP_QUEUE, retry=False
|
||||||
|
)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=5))
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()), "Scheduled"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_due_time_is_skipped_while_a_manual_backup_is_pending(self):
|
||||||
|
schedule = self.make_due()
|
||||||
|
manual_url = reverse(
|
||||||
|
"panel:account_backup_create", args=[self.account.pk]
|
||||||
|
)
|
||||||
|
self.assertEqual(self.client.post(manual_url).status_code, 302)
|
||||||
|
|
||||||
|
queue_due_account_backups(MONDAY)
|
||||||
|
job = self.account.backup_jobs.get()
|
||||||
|
self.assertIsNone(job.scheduled_for)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY + timedelta(days=1))
|
||||||
|
self.assertContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()), "Manual"
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_dates_and_job_are_unchanged_if_scheduling_fails(self):
|
||||||
|
schedule = self.make_due()
|
||||||
|
save = "coulobre.hosting.models.AccountBackupSchedule.save"
|
||||||
|
with (
|
||||||
|
patch(save, side_effect=RuntimeError),
|
||||||
|
self.assertRaises(RuntimeError),
|
||||||
|
):
|
||||||
|
queue_due_account_backups(MONDAY)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY)
|
||||||
|
self.assertFalse(self.account.backup_jobs.exists())
|
||||||
|
|
||||||
|
queue_due_account_backups(MONDAY)
|
||||||
|
self.assertEqual(self.account.backup_jobs.count(), 1)
|
||||||
|
|
||||||
|
@override_settings(LOCAL_ACCOUNT_BACKUPS=False)
|
||||||
|
def test_schedules_are_unavailable_when_local_backups_are_disabled(self):
|
||||||
|
schedule = self.make_due()
|
||||||
|
self.assertEqual(self.client.get(self.url).status_code, 404)
|
||||||
|
self.assertEqual(self.save_schedule().status_code, 404)
|
||||||
|
dispatch_account_backups()
|
||||||
|
self.assertFalse(self.account.backup_jobs.exists())
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertEqual(schedule.next_run_at, MONDAY)
|
||||||
|
|
||||||
|
@override_settings(LOCAL_ACCOUNT_BACKUP_MAIL=True)
|
||||||
|
def test_mail_schedule_captures_mailboxes_at_run_time(self):
|
||||||
|
with patch(
|
||||||
|
"coulobre.hosting.account_backups.timezone",
|
||||||
|
now=lambda: MONDAY - timedelta(hours=1),
|
||||||
|
):
|
||||||
|
self.assertEqual(
|
||||||
|
self.save_schedule(include_mailboxes="on").status_code, 302
|
||||||
|
)
|
||||||
|
domain = HostingMailDomain.objects.create(
|
||||||
|
account=self.account, domain="example.net"
|
||||||
|
)
|
||||||
|
mailbox = HostingMailbox.objects.create(
|
||||||
|
mail_domain=domain, local_part="support"
|
||||||
|
)
|
||||||
|
|
||||||
|
queue_due_account_backups(MONDAY)
|
||||||
|
job = self.account.backup_jobs.get()
|
||||||
|
self.assertEqual(
|
||||||
|
AccountBackup.from_manifest(job.manifest).mailboxes,
|
||||||
|
(mailbox.spec,),
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_existing_mail_schedule_can_be_paused_when_mail_is_disabled(self):
|
||||||
|
schedule = self.make_due(include_mailboxes=True)
|
||||||
|
response = self.save_schedule(include_mailboxes="on")
|
||||||
|
self.assertContains(response, "Enable local mailbox backups")
|
||||||
|
self.assertEqual(
|
||||||
|
self.save_schedule(enabled="", include_mailboxes="on").status_code,
|
||||||
|
302,
|
||||||
|
)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertFalse(schedule.enabled)
|
||||||
|
self.assertTrue(schedule.include_mailboxes)
|
||||||
|
queue_due_account_backups(MONDAY)
|
||||||
|
self.assertFalse(self.account.backup_jobs.exists())
|
||||||
|
|
||||||
|
@override_settings(LOCAL_ACCOUNT_BACKUP_MAIL=True)
|
||||||
|
def test_permissions_protect_schedules_and_their_mail_settings(self):
|
||||||
|
user = get_user_model().objects.create_user("limited-operator")
|
||||||
|
permissions = Permission.objects.filter(
|
||||||
|
content_type__app_label="hosting"
|
||||||
|
)
|
||||||
|
user.user_permissions.set(
|
||||||
|
permissions.filter(
|
||||||
|
codename__in=(
|
||||||
|
"view_hostingaccount",
|
||||||
|
"view_webprovisioningplan",
|
||||||
|
"view_hostingdatabase",
|
||||||
|
"add_accountbackupjob",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.client.force_login(user)
|
||||||
|
self.assertEqual(self.client.get(self.url).status_code, 403)
|
||||||
|
self.assertEqual(self.save_schedule().status_code, 403)
|
||||||
|
|
||||||
|
user.user_permissions.add(
|
||||||
|
permissions.get(codename="change_accountbackupschedule")
|
||||||
|
)
|
||||||
|
self.assertEqual(self.client.get(self.url).status_code, 200)
|
||||||
|
self.assertEqual(
|
||||||
|
self.save_schedule(include_mailboxes="on").status_code, 302
|
||||||
|
)
|
||||||
|
schedule = AccountBackupSchedule.objects.get(account=self.account)
|
||||||
|
self.assertFalse(schedule.include_mailboxes)
|
||||||
|
|
||||||
|
AccountBackupSchedule.objects.filter(pk=schedule.pk).update(
|
||||||
|
include_mailboxes=True
|
||||||
|
)
|
||||||
|
self.assertEqual(self.client.get(self.url).status_code, 403)
|
||||||
|
self.assertEqual(self.save_schedule().status_code, 403)
|
||||||
|
self.assertNotContains(
|
||||||
|
self.client.get(self.account.get_absolute_url()),
|
||||||
|
"Edit backup schedule",
|
||||||
|
)
|
||||||
|
schedule.refresh_from_db()
|
||||||
|
self.assertTrue(schedule.include_mailboxes)
|
||||||
|
|
||||||
|
Reseller.objects.create(user=user)
|
||||||
|
user.user_permissions.add(
|
||||||
|
permissions.get(codename="view_hostingmailbox")
|
||||||
|
)
|
||||||
|
self.assertEqual(self.save_schedule().status_code, 403)
|
||||||
@@ -40,6 +40,11 @@ urlpatterns = [
|
|||||||
views.RequestAccountBackup.as_view(),
|
views.RequestAccountBackup.as_view(),
|
||||||
name="account_backup_create",
|
name="account_backup_create",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"accounts/<int:pk>/backups/schedule/",
|
||||||
|
views.EditAccountBackupSchedule.as_view(),
|
||||||
|
name="account_backup_schedule",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"accounts/<int:pk>/sftp/",
|
"accounts/<int:pk>/sftp/",
|
||||||
views.SiteSFTPKeys.as_view(),
|
views.SiteSFTPKeys.as_view(),
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from django.conf import settings
|
|||||||
from django.contrib.auth import get_user_model
|
from django.contrib.auth import get_user_model
|
||||||
from django.contrib.auth.forms import UserCreationForm
|
from django.contrib.auth.forms import UserCreationForm
|
||||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import PermissionDenied, ValidationError
|
||||||
from django.db import IntegrityError, transaction
|
from django.db import IntegrityError, transaction
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
from django.http import (
|
from django.http import (
|
||||||
@@ -37,7 +37,12 @@ from .access import (
|
|||||||
is_tenant,
|
is_tenant,
|
||||||
reseller_for_user,
|
reseller_for_user,
|
||||||
)
|
)
|
||||||
from .account_backups import account_backup_manifest, queue_account_backup
|
from .account_backup_forms import SCHEDULE_FIELDS, AccountBackupScheduleForm
|
||||||
|
from .account_backups import (
|
||||||
|
account_backup_manifest,
|
||||||
|
queue_account_backup,
|
||||||
|
save_backup_schedule,
|
||||||
|
)
|
||||||
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 (
|
||||||
@@ -47,6 +52,7 @@ from .impersonation import (
|
|||||||
start_impersonation,
|
start_impersonation,
|
||||||
)
|
)
|
||||||
from .models import (
|
from .models import (
|
||||||
|
AccountBackupSchedule,
|
||||||
Customer,
|
Customer,
|
||||||
DatabaseProvisioning,
|
DatabaseProvisioning,
|
||||||
HostingAccount,
|
HostingAccount,
|
||||||
@@ -97,6 +103,10 @@ MANAGE_ACCOUNT_BACKUPS = (
|
|||||||
*EXPORT_BACKUP_MANIFEST,
|
*EXPORT_BACKUP_MANIFEST,
|
||||||
"hosting.add_accountbackupjob",
|
"hosting.add_accountbackupjob",
|
||||||
)
|
)
|
||||||
|
MANAGE_BACKUP_SCHEDULE = (
|
||||||
|
*MANAGE_ACCOUNT_BACKUPS,
|
||||||
|
"hosting.change_accountbackupschedule",
|
||||||
|
)
|
||||||
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 = (
|
||||||
@@ -306,6 +316,16 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|||||||
context["account_backup_allow_mail"] = (
|
context["account_backup_allow_mail"] = (
|
||||||
settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes
|
settings.LOCAL_ACCOUNT_BACKUP_MAIL and can_view_mailboxes
|
||||||
)
|
)
|
||||||
|
schedule = getattr(self.object, "backup_schedule", None)
|
||||||
|
if (
|
||||||
|
schedule is None
|
||||||
|
or not schedule.include_mailboxes
|
||||||
|
or can_view_mailboxes
|
||||||
|
):
|
||||||
|
context["account_backup_schedule"] = schedule
|
||||||
|
context["edit_account_backup_schedule"] = user.has_perms(
|
||||||
|
MANAGE_BACKUP_SCHEDULE
|
||||||
|
)
|
||||||
context["manage_sftp"] = (
|
context["manage_sftp"] = (
|
||||||
settings.LOCAL_WEB_SFTP
|
settings.LOCAL_WEB_SFTP
|
||||||
and can_manage_sftp(user)
|
and can_manage_sftp(user)
|
||||||
@@ -470,6 +490,61 @@ class RequestAccountBackup(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
|||||||
return redirect("panel:account", pk=pk)
|
return redirect("panel:account", pk=pk)
|
||||||
|
|
||||||
|
|
||||||
|
class EditAccountBackupSchedule(
|
||||||
|
OperatorOnlyMixin, PermissionRequiredMixin, FormView
|
||||||
|
):
|
||||||
|
permission_required = MANAGE_BACKUP_SCHEDULE
|
||||||
|
form_class = AccountBackupScheduleForm
|
||||||
|
template_name = "hosting/account_backup_schedule.html"
|
||||||
|
|
||||||
|
def dispatch(self, request, *args, **kwargs):
|
||||||
|
if not settings.LOCAL_ACCOUNT_BACKUPS:
|
||||||
|
raise Http404
|
||||||
|
return super().dispatch(request, *args, **kwargs)
|
||||||
|
|
||||||
|
@cached_property
|
||||||
|
def account(self):
|
||||||
|
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
||||||
|
|
||||||
|
def get_initial(self):
|
||||||
|
schedule = getattr(self.account, "backup_schedule", None)
|
||||||
|
if schedule is None:
|
||||||
|
return {
|
||||||
|
"enabled": True,
|
||||||
|
"frequency": AccountBackupSchedule.Frequency.DAILY,
|
||||||
|
}
|
||||||
|
if schedule.include_mailboxes and not self.request.user.has_perm(
|
||||||
|
VIEW_MAILBOXES
|
||||||
|
):
|
||||||
|
raise PermissionDenied
|
||||||
|
return {field: getattr(schedule, field) for field in SCHEDULE_FIELDS}
|
||||||
|
|
||||||
|
def get_form_kwargs(self):
|
||||||
|
kwargs = super().get_form_kwargs()
|
||||||
|
kwargs["allow_mail"] = (
|
||||||
|
settings.LOCAL_ACCOUNT_BACKUP_MAIL
|
||||||
|
and self.request.user.has_perm(VIEW_MAILBOXES)
|
||||||
|
)
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
def get_context_data(self, **kwargs):
|
||||||
|
return super().get_context_data(account=self.account, **kwargs)
|
||||||
|
|
||||||
|
def form_valid(self, form):
|
||||||
|
try:
|
||||||
|
save_backup_schedule(
|
||||||
|
self.account.pk,
|
||||||
|
can_manage_mail=self.request.user.has_perm(VIEW_MAILBOXES),
|
||||||
|
schedule_fields=form.cleaned_data,
|
||||||
|
)
|
||||||
|
except HostingAccount.DoesNotExist:
|
||||||
|
raise Http404 from None
|
||||||
|
return super().form_valid(form)
|
||||||
|
|
||||||
|
def get_success_url(self):
|
||||||
|
return self.account.get_absolute_url()
|
||||||
|
|
||||||
|
|
||||||
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"
|
||||||
|
|||||||
Reference in new issue
Block a user