From 57e5a29844fdcd1592b150a701f5a0a8f0db00ea Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Tue, 1 Dec 2026 14:22:35 +0100 Subject: [PATCH] Email scoped hosting and server notifications after outcomes Refs #223. --- src/coulobre/hosting/account_setup.py | 13 +- .../commands/collect_service_health.py | 37 ++- .../migrations/0084_panel_notifications.py | 141 +++++++++ src/coulobre/hosting/models.py | 57 ++++ src/coulobre/hosting/notification_views.py | 66 ++++ src/coulobre/hosting/notifications.py | 288 ++++++++++++++++++ src/coulobre/hosting/offsite_backups.py | 31 +- src/coulobre/hosting/tasks.py | 20 +- .../templates/hosting/account_security.html | 1 + .../hosting/notification_preferences.html | 43 +++ src/coulobre/hosting/test_notifications.py | 123 ++++++++ src/coulobre/hosting/urls.py | 6 + src/coulobre/settings.py | 6 + 13 files changed, 813 insertions(+), 19 deletions(-) create mode 100644 src/coulobre/hosting/migrations/0084_panel_notifications.py create mode 100644 src/coulobre/hosting/notification_views.py create mode 100644 src/coulobre/hosting/notifications.py create mode 100644 src/coulobre/hosting/templates/hosting/notification_preferences.html create mode 100644 src/coulobre/hosting/test_notifications.py diff --git a/src/coulobre/hosting/account_setup.py b/src/coulobre/hosting/account_setup.py index 9f22cc2..cbceeca 100644 --- a/src/coulobre/hosting/account_setup.py +++ b/src/coulobre/hosting/account_setup.py @@ -21,6 +21,7 @@ from .models import ( WebsiteAlias, WebsiteDomain, ) +from .notifications import notify_creation from .php_settings import plan_php_settings from .resource_requests import create_mailbox_request @@ -92,9 +93,15 @@ def setup_new_account(account, options): ) if mail_domain.account_id != account.pk: raise ValidationError("This domain already has email configured.") - if options.get("setup_info_mailbox"): - return setup_info_mailbox(account, options.get("setup_email")) - return "" + notice = ( + setup_info_mailbox(account, options.get("setup_email")) + if options.get("setup_info_mailbox") + else "" + ) + notify_creation( + account, "Hosting account created", f"account:{account.pk}" + ) + return notice def setup_info_mailbox(account, managed_mail): diff --git a/src/coulobre/hosting/management/commands/collect_service_health.py b/src/coulobre/hosting/management/commands/collect_service_health.py index a172138..fa16e98 100644 --- a/src/coulobre/hosting/management/commands/collect_service_health.py +++ b/src/coulobre/hosting/management/commands/collect_service_health.py @@ -1,9 +1,35 @@ from django.conf import settings from django.core.management.base import BaseCommand +from django.db import transaction from django.utils import timezone from coulobre.hosting.models import ServiceHealth -from coulobre.service_health import read_health +from coulobre.hosting.notifications import notify_health +from coulobre.service_health import HealthResult, read_health + + +@transaction.atomic +def record_health(node, service, result, observed_at): + readings = ServiceHealth.objects.select_for_update() + reading, created = readings.get_or_create( + node=node, + service=service, + defaults={"result": result, "observed_at": observed_at}, + ) + if not created and reading.observed_at >= observed_at: + return + outage = ( + reading.outage + if result == HealthResult.TRANSITIONING + else result != HealthResult.ACTIVE + ) + changed = reading.outage != outage + reading.outage = outage + reading.result = result + reading.observed_at = observed_at + reading.save(update_fields=["outage", "result", "observed_at"]) + if changed: + notify_health(reading) class Command(BaseCommand): @@ -13,11 +39,4 @@ class Command(BaseCommand): for target in settings.SERVICE_HEALTH_TARGETS: observed_at = timezone.now() for service, result in read_health(target).items(): - values = {"result": result, "observed_at": observed_at} - reading, created = ServiceHealth.objects.get_or_create( - node=target.node, service=service, defaults=values - ) - if not created: - ServiceHealth.objects.filter( - pk=reading.pk, observed_at__lte=observed_at - ).update(**values) + record_health(target.node, service, result, observed_at) diff --git a/src/coulobre/hosting/migrations/0084_panel_notifications.py b/src/coulobre/hosting/migrations/0084_panel_notifications.py new file mode 100644 index 0000000..e80c2f2 --- /dev/null +++ b/src/coulobre/hosting/migrations/0084_panel_notifications.py @@ -0,0 +1,141 @@ +# Generated by Django 5.2.19 on 2026-12-01 13:20 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0083_mailboxremoval"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name="servicehealth", + name="outage", + field=models.BooleanField(default=False), + ), + migrations.CreateModel( + name="NotificationPreferences", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "creation", + models.BooleanField( + default=False, + verbose_name="Hosting and resource setup", + ), + ), + ( + "backup_failures", + models.BooleanField( + default=False, + verbose_name="Backup, transfer and restore failures", + ), + ), + ( + "backup_successes", + models.BooleanField( + default=False, + verbose_name="Manual backup and restore completions", + ), + ), + ( + "backup_summary", + models.BooleanField( + default=False, + verbose_name="Daily summary of scheduled backups", + ), + ), + ( + "health", + models.BooleanField( + default=False, + verbose_name="Service outages and recoveries", + ), + ), + ( + "user", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="notification_preferences", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + ), + migrations.CreateModel( + name="PanelNotification", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("category", models.CharField(max_length=20)), + ("reference", models.CharField(max_length=160)), + ("resource", models.CharField(max_length=320)), + ("outcome", models.CharField(max_length=80)), + ("scope", models.CharField(max_length=8)), + ( + "state", + models.CharField( + choices=[ + ("pending", "Pending"), + ("sending", "Sending"), + ("sent", "Sent"), + ("failed", "Delivery failed"), + ("skipped", "Skipped"), + ], + default="pending", + max_length=8, + ), + ), + ("created_at", models.DateTimeField(auto_now_add=True)), + ("attempted_at", models.DateTimeField(null=True)), + ( + "account", + models.ForeignKey( + null=True, + on_delete=django.db.models.deletion.CASCADE, + to="hosting.hostingaccount", + ), + ), + ( + "recipient", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "indexes": [ + models.Index( + fields=["state", "created_at"], + name="hosting_pan_state_d545c5_idx", + ) + ], + "constraints": [ + models.UniqueConstraint( + fields=("recipient", "reference"), + name="unique_panel_notification", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index d976cb2..bd19146 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1569,6 +1569,7 @@ class ServiceHealth(models.Model): service = models.CharField(max_length=24) result = models.CharField(max_length=24) observed_at = models.DateTimeField() + outage = models.BooleanField(default=False) class Meta: default_permissions = ("view",) @@ -1580,6 +1581,62 @@ class ServiceHealth(models.Model): ] +class NotificationPreferences(models.Model): + user = models.OneToOneField( + settings.AUTH_USER_MODEL, + on_delete=models.CASCADE, + related_name="notification_preferences", + ) + creation = models.BooleanField("Hosting and resource setup", default=False) + backup_failures = models.BooleanField( + "Backup, transfer and restore failures", default=False + ) + backup_successes = models.BooleanField( + "Manual backup and restore completions", default=False + ) + backup_summary = models.BooleanField( + "Daily summary of scheduled backups", default=False + ) + health = models.BooleanField( + "Service outages and recoveries", default=False + ) + + +class PanelNotification(models.Model): + class State(models.TextChoices): + PENDING = "pending", "Pending" + SENDING = "sending", "Sending" + SENT = "sent", "Sent" + FAILED = "failed", "Delivery failed" + SKIPPED = "skipped", "Skipped" + + recipient = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.CASCADE + ) + category = models.CharField(max_length=20) + reference = models.CharField(max_length=160) + resource = models.CharField(max_length=320) + outcome = models.CharField(max_length=80) + account = models.ForeignKey( + HostingAccount, on_delete=models.CASCADE, null=True + ) + scope = models.CharField(max_length=8) + state = models.CharField( + max_length=8, choices=State, default=State.PENDING + ) + created_at = models.DateTimeField(auto_now_add=True) + attempted_at = models.DateTimeField(null=True) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("recipient", "reference"), + name="unique_panel_notification", + ) + ] + indexes = [models.Index(fields=("state", "created_at"))] + + class SignInWindow(models.Model): digest = models.CharField(max_length=64) slot = models.PositiveBigIntegerField(db_index=True) diff --git a/src/coulobre/hosting/notification_views.py b/src/coulobre/hosting/notification_views.py new file mode 100644 index 0000000..c154d85 --- /dev/null +++ b/src/coulobre/hosting/notification_views.py @@ -0,0 +1,66 @@ +from django import forms +from django.contrib import messages +from django.shortcuts import redirect +from django.views.generic import FormView + +from .account_security import AccountSecurityMixin +from .models import NotificationPreferences, PanelNotification +from .notifications import notifications_available + + +class NotificationPreferencesForm(forms.ModelForm): + class Meta: + model = NotificationPreferences + fields = ( + "creation", + "backup_failures", + "backup_successes", + "backup_summary", + "health", + ) + + +class NotificationPreferencesView(AccountSecurityMixin, FormView): + form_class = NotificationPreferencesForm + template_name = "hosting/notification_preferences.html" + + def get_form_kwargs(self): + user = self.request.user + preferences = getattr(user, "notification_preferences", None) + if preferences is None: + preferences = NotificationPreferences(user=user) + return super().get_form_kwargs() | {"instance": preferences} + + def get_form(self, form_class=None): + form = super().get_form(form_class) + if not self.request.user.is_superuser: + form.fields.pop("health") + form.fields.pop("backup_summary") + return form + + def form_valid(self, form): + NotificationPreferences.objects.update_or_create( + user=self.request.user, defaults=form.cleaned_data + ) + messages.success(self.request, "Email preferences saved.") + return redirect("panel:notifications") + + def get_context_data(self, **kwargs): + user = self.request.user + deliveries = PanelNotification.objects.filter(recipient=user) + failures = ( + PanelNotification.objects.filter( + state=PanelNotification.State.FAILED + ) + .exclude(recipient=user) + .select_related("recipient") + .order_by("-pk")[:30] + if user.is_superuser and user.is_verified() + else () + ) + return super().get_context_data( + email_available=notifications_available(), + deliveries=deliveries.order_by("-pk")[:20], + failures=failures, + **kwargs, + ) diff --git a/src/coulobre/hosting/notifications.py b/src/coulobre/hosting/notifications.py new file mode 100644 index 0000000..f9a2fe9 --- /dev/null +++ b/src/coulobre/hosting/notifications.py @@ -0,0 +1,288 @@ +from datetime import UTC, timedelta +from smtplib import SMTPException + +from django.conf import settings +from django.core.exceptions import ValidationError +from django.core.mail import send_mail +from django.core.validators import validate_email +from django.db.models import Count +from django.urls import reverse +from django.utils import timezone + +from coulobre.service_health import SERVICES + +from .models import ( + AccountBackupJob, + ComponentRestoreJob, + DatabaseProvisioning, + DnsPublication, + HostingAccount, + IndependentWebsite, + MailboxProvisioning, + NotificationPreferences, + PanelNotification, + SystemBackupJob, + WebActivation, + WebsiteRestoreJob, +) + +State = PanelNotification.State +ATTEMPT_TIMEOUT = timedelta(minutes=5) + + +def notifications_available(): + return bool(settings.EMAIL_HOST and settings.PASSWORD_RESET_ORIGIN) + + +def queue_notification( + category, + reference, + resource, + outcome, + *, + account=None, + customer_visible=True, +): + if not notifications_available(): + return + subscribers = NotificationPreferences.objects.filter( + user__is_active=True, **{category: True} + ).exclude(user__email="") + scopes = { + user_id: "operator" + for user_id in subscribers.filter(user__is_superuser=True).values_list( + "user_id", flat=True + ) + } + if account is not None and account.retired_at is None: + if account.customer_id and customer_visible: + customer_id = account.customer.user_id + if subscribers.filter(user_id=customer_id).exists(): + scopes.setdefault(customer_id, "customer") + if category == "creation" and account.reseller_id: + manager_id = account.reseller.user_id + if subscribers.filter(user_id=manager_id).exists(): + scopes.setdefault(manager_id, "manager") + PanelNotification.objects.bulk_create( + [ + PanelNotification( + recipient_id=user_id, + category=category, + reference=reference, + resource=resource, + outcome=outcome, + account=account, + scope=scope, + ) + for user_id, scope in scopes.items() + ], + ignore_conflicts=True, + ) + + +def notify_creation(account, label, reference, *, failed=False): + outcome = "Needs attention" if failed else "Ready" + queue_notification( + "creation", + f"creation:{reference}:{failed}", + f"{label} · {account.primary_domain}", + outcome, + account=account, + ) + + +def notify_backup( + job, account, label, *, failed, scheduled=False, customer_id=None +): + if scheduled and not failed: + return + queue_notification( + "backup_failures" if failed else "backup_successes", + f"backup:{job._meta.model_name}:{job.pk}:{failed}", + f"{label} · {account.primary_domain}" + if account is not None + else label, + "Needs attention" if failed else "Completed", + account=account, + customer_visible=bool( + account and customer_id and account.customer_id == customer_id + ), + ) + + +def notify_health(reading): + label = SERVICES[reading.service][0] + queue_notification( + "health", + f"health:{reading.pk}:{reading.observed_at.isoformat()}", + f"{label} · {reading.node}", + "Unavailable" if reading.outage else "Recovered", + ) + + +def notify_job_outcome(job, *, failed): + match job: + case WebActivation(): + account, resource = job.plan.account, "Primary website" + case IndependentWebsite() if ( + job.operation == IndependentWebsite.Operation.ACTIVATE + ): + account, resource = job.reservation.account, "Website" + case DatabaseProvisioning(): + account, resource = job.database.account, "Database" + case DnsPublication() if job.published_serial is None: + account, resource = job.zone.account, "DNS zone publication" + case MailboxProvisioning() if not job.quota_update: + account, resource = job.mailbox.mail_domain.account, "Mailbox" + case AccountBackupJob(): + return notify_backup( + job, + job.account, + "Backup", + failed=failed, + scheduled=job.scheduled_for is not None, + customer_id=job.export_customer_id, + ) + case WebsiteRestoreJob() | ComponentRestoreJob(): + return notify_backup( + job, + job.backup.account, + "Restore", + failed=failed, + customer_id=job.requested_customer_id, + ) + case SystemBackupJob(): + return notify_backup( + job, + None, + "System backup", + failed=failed, + scheduled=job.scheduled_for is not None, + ) + case _: + return + notify_creation( + account, resource, f"{job._meta.model_name}:{job.pk}", failed=failed + ) + + +def queue_backup_summaries(now): + end = now.astimezone(UTC).replace( + hour=0, minute=0, second=0, microsecond=0 + ) + start = end - timedelta(days=1) + if not NotificationPreferences.objects.filter( + backup_summary=True + ).exists(): + return + counts = ( + AccountBackupJob.objects.filter( + scheduled_for__isnull=False, + finished_at__gte=start, + finished_at__lt=end, + problem="", + archive_bytes__isnull=False, + export_customer_id__isnull=True, + ) + .values("account_id") + .annotate(total=Count("pk")) + ) + grouped = {row["account_id"]: row for row in counts} + for account in HostingAccount.objects.filter( + pk__in=grouped + ).select_related("customer", "reseller"): + total = grouped[account.pk]["total"] + queue_notification( + "backup_summary", + f"backup-summary:{account.pk}:{start.date()}", + f"Scheduled backups · {account.primary_domain}", + f"{total} completed on {start.date()} (UTC)", + account=account, + customer_visible=False, + ) + + +def authorized_recipient(notification): + user = notification.recipient + preferences = getattr(user, "notification_preferences", None) + if ( + not user.is_active + or preferences is None + or not getattr(preferences, notification.category) + ): + return False + if notification.scope == "operator": + return user.is_superuser + account = notification.account + if account is None or account.retired_at is not None: + return False + if notification.scope == "manager": + return ( + account.reseller is not None + and account.reseller.user_id == user.pk + ) + return account.customer is not None and account.customer.user_id == user.pk + + +def notification_path(notification): + if notification.category == "health": + return reverse("panel:service_health") + account_id = notification.account_id + if account_id is None: + return reverse("panel:system_backup") + if notification.category == "creation": + return notification.account.get_absolute_url() + if notification.scope == "customer": + return reverse("panel:customer_backups", args=[account_id]) + return notification.account.get_absolute_url() + "#backups" + + +def deliver_pending_notifications(): + if not notifications_available(): + return + now = timezone.now() + PanelNotification.objects.filter( + state=State.SENDING, attempted_at__lt=now - ATTEMPT_TIMEOUT + ).update(state=State.FAILED) + pending = PanelNotification.objects.filter(state=State.PENDING) + for pk in list(pending.order_by("pk").values_list("pk", flat=True)[:50]): + if not pending.filter(pk=pk).update( + state=State.SENDING, attempted_at=now + ): + continue + notification = ( + PanelNotification.objects.select_related( + "recipient__notification_preferences", + "account__customer", + "account__reseller", + ) + .filter(pk=pk) + .first() + ) + if notification is None: + continue + outcome = State.SKIPPED + if authorized_recipient(notification): + outcome = send_notification(notification) + PanelNotification.objects.filter(pk=pk, state=State.SENDING).update( + state=outcome + ) + + +def send_notification(notification): + email = notification.recipient.email + try: + validate_email(email) + path = notification_path(notification) + origin = settings.PASSWORD_RESET_ORIGIN.rstrip("/") + subject = f"Coulobre Panel · {notification.resource}" + body = ( + f"{notification.resource}\n" + f"{notification.outcome}\n\n" + f"Open Coulobre Panel for details\n{origin}{path}\n" + ) + if send_mail(subject, body, settings.DEFAULT_FROM_EMAIL, [email]) == 1: + return State.SENT + except (OSError, SMTPException, ValueError, ValidationError): + pass + return State.FAILED diff --git a/src/coulobre/hosting/offsite_backups.py b/src/coulobre/hosting/offsite_backups.py index 54c03a9..9d0eb6b 100644 --- a/src/coulobre/hosting/offsite_backups.py +++ b/src/coulobre/hosting/offsite_backups.py @@ -15,6 +15,7 @@ from coulobre.offsite_backup import ( from .models import OffsiteBackupTransfer from .node_client import apply_on_local_node +from .notifications import notify_backup OFFSITE_BACKUP_QUEUE = "coulobre-offsite-backups" OFFSITE_BACKUP_LEASE = timedelta(seconds=TRANSFER_TIMEOUT_SECONDS + 60) @@ -35,11 +36,28 @@ def transfer_scope(now): def finish_interrupted_transfers(now): - OffsiteBackupTransfer.objects.filter( + waiting = OffsiteBackupTransfer.objects.filter( finished_at__isnull=True, started_at__lte=now - OFFSITE_BACKUP_LEASE, attempts__gte=MAX_ATTEMPTS, - ).update(finished_at=now, problem=TRANSFER_PROBLEM) + ) + for job in waiting.select_related("backup__account").iterator(): + finish_transfer( + waiting.filter(pk=job.pk), job, now, problem=TRANSFER_PROBLEM + ) + + +@transaction.atomic +def finish_transfer(running, job, finished, *, problem="", **fields): + if running.update(finished_at=finished, problem=problem, **fields): + notify_backup( + job, + job.backup.account, + "Off-site backup transfer", + failed=bool(problem), + scheduled=job.backup.scheduled_for is not None, + customer_id=job.backup.export_customer_id, + ) def apply_offsite_transfer(job): @@ -89,7 +107,7 @@ def run_offsite_transfer(job_id): except (OSError, ValueError): finished = timezone.now() if job.attempts >= MAX_ATTEMPTS: - running.update(finished_at=finished, problem=TRANSFER_PROBLEM) + finish_transfer(running, job, finished, problem=TRANSFER_PROBLEM) else: delay = timedelta(minutes=5 * 2 ** (job.attempts - 1)) running.update( @@ -100,12 +118,13 @@ def run_offsite_transfer(job_id): ) else: finished = timezone.now() - running.update( - finished_at=finished, + finish_transfer( + running, + job, + finished, verified_at=finished, snapshot=snapshot, sha256=digest, - problem="", ) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index c147384..fc13182 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -94,6 +94,12 @@ from .node_client import ( update_local_sftp, update_local_website_alias, ) +from .notifications import ( + deliver_pending_notifications, + notifications_available, + notify_job_outcome, + queue_backup_summaries, +) from .offsite_backups import ( MAX_ATTEMPTS as MAX_OFFSITE_ATTEMPTS, ) @@ -1098,7 +1104,19 @@ def run_provisioning_job( problem = connection_problem except ValueError as error: problem = str(error) - running.update(finished_at=timezone.now(), problem=problem, **updates) + with transaction.atomic(): + completed = running.update( + finished_at=timezone.now(), problem=problem, **updates + ) + if completed and notifications_available(): + notify_job_outcome(job, failed=bool(problem)) + + +@shared_task +def deliver_panel_notifications(): + if notifications_available(): + queue_backup_summaries(timezone.now()) + deliver_pending_notifications() @shared_task diff --git a/src/coulobre/hosting/templates/hosting/account_security.html b/src/coulobre/hosting/templates/hosting/account_security.html index c3037cc..f0296ec 100644 --- a/src/coulobre/hosting/templates/hosting/account_security.html +++ b/src/coulobre/hosting/templates/hosting/account_security.html @@ -13,6 +13,7 @@
Change password Choose theme + Email notifications {% if email_available %}Change email address{% endif %} {% if factor_enabled %}Change{% else %}Set up{% endif %} authenticator app {% if factor_enabled %}Generate recovery codes{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/notification_preferences.html b/src/coulobre/hosting/templates/hosting/notification_preferences.html new file mode 100644 index 0000000..0f54e5a --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/notification_preferences.html @@ -0,0 +1,43 @@ +{% extends "hosting/workspace_page.html" %} + +{% block title %}Email notifications · Coulobre Panel{% endblock %} +{% block page_title %}Email notifications{% endblock %} +{% block page_actions %}← My account{% endblock %} +{% block page_content %} +
+ {% if not email_available %} +

Notifications require configured panel email delivery.

+ {% elif not request.user.email %} +

Set your email address to receive notifications.

+ {% else %} +

Send the selected notifications to {{ request.user.email }}.

+ {% endif %} +
+ {% csrf_token %} + {{ form.as_p }} + +
+
+ {% if deliveries %} +
+

Recent deliveries

+
+ + {% for delivery in deliveries %} + + {% endfor %} +
EventOutcomeEmail
{{ delivery.resource }}{{ delivery.outcome }}{{ delivery.get_state_display }}
+
+ {% endif %} + {% if failures %} +
+

Recent delivery failures

+
+ + {% for delivery in failures %} + + {% endfor %} +
EventRecipientAttempted (UTC)
{{ delivery.resource }}{{ delivery.recipient.get_username }}{{ delivery.attempted_at|date:"j M Y, H:i" }}
+
+ {% endif %} +{% endblock %} diff --git a/src/coulobre/hosting/test_notifications.py b/src/coulobre/hosting/test_notifications.py new file mode 100644 index 0000000..38d6071 --- /dev/null +++ b/src/coulobre/hosting/test_notifications.py @@ -0,0 +1,123 @@ +from datetime import timedelta +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core import mail +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone + +from coulobre.service_health import HealthResult + +from .management.commands.collect_service_health import record_health +from .models import ( + Customer, + DatabaseProvisioning, + HostingAccount, + HostingDatabase, + NotificationPreferences, + PanelNotification, +) +from .notifications import deliver_pending_notifications, notify_creation +from .tasks import provision_database + + +@override_settings( + EMAIL_HOST="smtp.example.test", + PASSWORD_RESET_ORIGIN="https://panel.example.test", + LOCAL_DATABASE_PROVISIONING=True, +) +class NotificationTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.operator = users.create_superuser("operator", "ops@example.test") + cls.customer = users.create_user("customer", "owner@example.test") + cls.other = users.create_user("other", "other@example.test") + cls.account = HostingAccount.objects.create( + name="Example site", + primary_domain="site.example", + customer=Customer.objects.create(user=cls.customer), + ) + NotificationPreferences.objects.create( + user=cls.operator, creation=True, health=True + ) + NotificationPreferences.objects.create( + user=cls.customer, creation=True + ) + NotificationPreferences.objects.create( + user=cls.other, creation=True, health=True + ) + + def test_scopes_and_deduplication_across_provisioning_retries(self): + job = DatabaseProvisioning.objects.create( + database=HostingDatabase.objects.create( + account=self.account, suffix="app" + ) + ) + for error in ( + OSError("private host information"), + OSError("private error"), + None, + ): + with patch( + "coulobre.hosting.tasks.provision_local_database", + side_effect=error, + ): + provision_database.run(job.pk) + job.refresh_from_db() + self.assertIsNotNone(job.finished_at) + if error is not None: + DatabaseProvisioning.objects.requeue( + DatabaseProvisioning.objects.filter(pk=job.pk) + ) + self.assertEqual(PanelNotification.objects.count(), 4) + deliver_pending_notifications() + deliver_pending_notifications() + self.assertEqual(len(mail.outbox), 4) + self.assertEqual( + {message.to[0] for message in mail.outbox}, + {self.operator.email, self.customer.email}, + ) + for message in mail.outbox: + self.assertNotIn("private", message.body) + self.assertIn( + "https://panel.example.test" + self.account.get_absolute_url(), + message.body, + ) + + def test_outage_and_recovery_only(self): + now = timezone.now() + results = ( + HealthResult.ACTIVE, + HealthResult.INACTIVE, + HealthResult.FAILED, + HealthResult.TRANSITIONING, + HealthResult.ACTIVE, + ) + for offset, result in enumerate(results): + record_health( + "panel", "apache", result, now + timedelta(minutes=offset) + ) + deliver_pending_notifications() + self.assertEqual(len(mail.outbox), 2) + self.assertIn("Unavailable", mail.outbox[0].body) + self.assertIn("Recovered", mail.outbox[1].body) + self.assertEqual( + {message.to[0] for message in mail.outbox}, {self.operator.email} + ) + + def test_delivery_failure_is_visible_and_moved_account_is_skipped(self): + notify_creation(self.account, "Account", "test") + HostingAccount.objects.filter(pk=self.account.pk).update(customer=None) + with patch( + "coulobre.hosting.notifications.send_mail", side_effect=OSError + ): + deliver_pending_notifications() + self.assertEqual( + PanelNotification.objects.get(recipient=self.customer).state, + "skipped", + ) + self.client.force_login(self.operator) + response = self.client.get(reverse("panel:notifications")) + self.assertContains(response, "Delivery failed") diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 35b17db..6c62e42 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -57,6 +57,7 @@ from .mail_policy_views import ( ) from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action from .mailbox_removal import MailboxRemovalView +from .notification_views import NotificationPreferencesView from .operator_backups import OperatorBackupsView from .operator_tools import ( ConnectedNodesView, @@ -373,6 +374,11 @@ urlpatterns = [ path( "my-account/", AccountSecurityView.as_view(), name="account_security" ), + path( + "my-account/notifications/", + NotificationPreferencesView.as_view(), + name="notifications", + ), path( "my-account/password/", ChangePasswordView.as_view(), diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 7dafcaf..7337f05 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -440,6 +440,12 @@ CELERY_BEAT_SCHEDULE = { "options": {"expires": 5.0}, }, } +if EMAIL_HOST and PASSWORD_RESET_ORIGIN: + CELERY_BEAT_SCHEDULE["deliver-panel-notifications"] = { + "task": "coulobre.hosting.tasks.deliver_panel_notifications", + "schedule": 60.0, + "options": {"expires": 55.0}, + } if LOCAL_WEB_ACTIVATION: CELERY_BEAT_SCHEDULE["dispatch-web-activations"] = { "task": "coulobre.hosting.tasks.dispatch_web_activations",