Files
coulobre/src/coulobre/hosting/tasks.py
T

682 lines
21 KiB
Python
Raw Normal View History

2026-11-19 21:18:37 +01:00
from datetime import timedelta
from uuid import UUID
2026-11-19 21:18:37 +01:00
from celery import shared_task
from django.conf import settings
from django.db import transaction
2026-11-19 21:18:37 +01:00
from django.db.models import Q
from django.utils import timezone
2026-11-21 12:35:24 +01:00
from coulobre.account_backup import AccountBackup
from coulobre.account_backup_request import (
BACKUP_TIMEOUT_SECONDS,
AccountBackupRequest,
)
from coulobre.account_backup_retention import ArchiveExpirationRequest
from coulobre.account_restore_request import (
RESTORE_TIMEOUT_SECONDS,
ComponentRestoreRequest,
WebsiteRestoreRequest,
)
2026-11-21 01:41:06 +01:00
from coulobre.dns_node import DnsZone
from coulobre.php_pool_settings import PhpPoolSettings
from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebAlias, WebSite
from .account_backups import queue_due_account_backups
from .backup_restores import (
available_restore_resources,
current_restore_resources,
enabled_component_restores,
)
from .backup_retention import plan_backup_expirations
2026-11-21 01:41:06 +01:00
from .models import (
AccountBackupExpiration,
2026-11-21 12:35:24 +01:00
AccountBackupJob,
ComponentRestoreJob,
2026-11-21 01:41:06 +01:00
DatabaseProvisioning,
DnsPublication,
MailboxProvisioning,
SitePhpSettings,
SiteSFTP,
SiteStorageLimit,
SiteStorageUsage,
2026-11-21 01:41:06 +01:00
WebActivation,
WebHTTPS,
2026-11-21 01:41:06 +01:00
WebProvisioningPlan,
WebsiteAlias,
WebsiteRestoreJob,
2026-11-21 01:41:06 +01:00
)
from .node_client import (
activate_local_site,
activate_local_site_with_php,
2026-11-21 12:35:24 +01:00
create_local_account_backup,
enable_local_https,
expire_local_account_backup,
measure_local_site_storage,
2026-11-21 01:41:06 +01:00
provision_local_database,
provision_local_mailbox,
2026-11-21 01:41:06 +01:00
publish_local_zone,
restore_local_component,
restore_local_website,
set_local_site_storage_limit,
update_local_mailbox_quota,
update_local_php_settings,
update_local_sftp,
update_local_website_alias,
2026-11-21 01:41:06 +01:00
)
from .sftp import site_is_active
2026-11-19 21:18:37 +01:00
REDISPATCH_AFTER = timedelta(minutes=5)
2026-11-21 12:35:24 +01:00
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
ACCOUNT_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60)
2026-11-21 12:35:24 +01:00
ACCOUNT_BACKUP_QUEUE = "coulobre-account-backups"
UNCONFIRMED_RESTORE = (
"Could not confirm the restore on the local backup node. "
"Check the destination before requesting another restore."
)
WEB_ACTIVATION_QUEUE = "coulobre-web-activation"
WEB_HTTPS_QUEUE = "coulobre-web-https"
WEB_SFTP_QUEUE = "coulobre-web-sftp"
DATABASE_PROVISIONING_QUEUE = "coulobre-database-provisioning"
2026-11-21 01:41:06 +01:00
DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing"
MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning"
2026-11-19 21:18:37 +01:00
@shared_task
def dispatch_web_plans():
stale_before = timezone.now() - REDISPATCH_AFTER
pending_ids = (
WebProvisioningPlan.objects.filter(completed_at__isnull=True)
.filter(
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before)
2026-11-19 21:18:37 +01:00
)
.order_by("requested_at", "pk")
.values_list("pk", flat=True)[:100]
)
for plan_id in list(pending_ids):
render_web_plan.apply_async(args=[plan_id], retry=False)
WebProvisioningPlan.objects.filter(
pk=plan_id, completed_at__isnull=True
).update(last_dispatched_at=timezone.now())
@shared_task(acks_late=True, reject_on_worker_lost=True)
def render_web_plan(plan_id):
pending = WebProvisioningPlan.objects.filter(
pk=plan_id, completed_at__isnull=True
)
2026-11-19 21:18:37 +01:00
plan = pending.first()
if plan is None:
return
apache_config = WebSite(plan.account_id, plan.primary_domain).render(
"apache"
)
2026-11-19 21:18:37 +01:00
pending.update(apache_config=apache_config, completed_at=timezone.now())
@shared_task
def dispatch_web_activations():
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE
)
dispatch_provisioning_jobs(
WebsiteAlias,
update_website_alias,
WEB_ACTIVATION_QUEUE,
operation__in=(
WebsiteAlias.Operation.ACTIVATE,
WebsiteAlias.Operation.REMOVE,
),
)
dispatch_provisioning_jobs(
SitePhpSettings, set_site_php_settings, WEB_ACTIVATION_QUEUE
)
@shared_task
def dispatch_site_storage_measurements():
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
SiteStorageUsage, measure_site_storage, WEB_ACTIVATION_QUEUE
)
@shared_task
def dispatch_site_storage_limits():
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
SiteStorageLimit, set_site_storage_limit, WEB_ACTIVATION_QUEUE
)
@shared_task
def dispatch_web_https():
if settings.LOCAL_WEB_HTTPS:
dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE)
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
WebsiteAlias,
enable_website_alias_https,
WEB_HTTPS_QUEUE,
operation=WebsiteAlias.Operation.HTTPS,
)
@shared_task
def dispatch_web_sftp():
if settings.LOCAL_WEB_SFTP:
dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE)
@shared_task
def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING:
dispatch_provisioning_jobs(
DatabaseProvisioning,
provision_database,
DATABASE_PROVISIONING_QUEUE,
)
2026-11-21 01:41:06 +01:00
@shared_task
def dispatch_dns_publications():
if settings.LOCAL_DNS_PUBLISHING:
dispatch_provisioning_jobs(
DnsPublication, publish_dns_zone, DNS_PUBLISHING_QUEUE
)
@shared_task
def dispatch_mailbox_provisioning():
if settings.LOCAL_MAILBOX_PROVISIONING:
dispatch_provisioning_jobs(
MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE
)
2026-11-21 12:35:24 +01:00
@shared_task
def dispatch_account_backups():
if settings.LOCAL_ACCOUNT_BACKUPS:
queue_due_account_backups(timezone.now())
2026-11-21 12:35:24 +01:00
dispatch_provisioning_jobs(
AccountBackupJob,
create_account_backup,
ACCOUNT_BACKUP_QUEUE,
lease=ACCOUNT_BACKUP_LEASE,
)
if settings.LOCAL_WEBSITE_RESTORE:
dispatch_provisioning_jobs(
WebsiteRestoreJob,
restore_website,
ACCOUNT_BACKUP_QUEUE,
lease=ACCOUNT_RESTORE_LEASE,
)
kinds = enabled_component_restores()
if kinds:
dispatch_provisioning_jobs(
ComponentRestoreJob,
restore_backup_component,
ACCOUNT_BACKUP_QUEUE,
lease=ACCOUNT_RESTORE_LEASE,
kind__in=kinds,
)
if settings.LOCAL_BACKUP_RETENTION:
dispatch_provisioning_jobs(
AccountBackupExpiration,
expire_account_backup,
ACCOUNT_BACKUP_QUEUE,
lease=ACCOUNT_BACKUP_LEASE,
)
@shared_task
def plan_account_backup_expirations():
if settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_BACKUP_RETENTION:
plan_backup_expirations(timezone.now())
2026-11-21 12:35:24 +01:00
def dispatch_provisioning_jobs(
model, task, queue, *, lease=REDISPATCH_AFTER, **scope
):
2026-11-21 12:35:24 +01:00
now = timezone.now()
stale_before = now - REDISPATCH_AFTER
waiting = model.objects.filter(finished_at__isnull=True, **scope)
pending = (
waiting.filter(
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before)
)
2026-11-21 12:35:24 +01:00
.filter(Q(started_at__isnull=True) | Q(started_at__lte=now - lease))
.order_by("requested_at", "pk")
.values_list("pk", "requested_at")[:100]
)
for job_id, requested_at in list(pending):
task.apply_async(args=[job_id], queue=queue, retry=False)
waiting.filter(pk=job_id, requested_at=requested_at).update(
last_dispatched_at=timezone.now()
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def activate_web_plan(activation_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
WebActivation.objects.select_related("plan__account"),
activation_id,
apply_web_activation,
"Could not complete the request to the local web node. "
"Check its socket and try again.",
)
def apply_web_activation(activation):
plan = activation.plan
if not plan.can_export:
raise ValueError(
"Request a completed Apache preview for the current "
"account domain."
)
site = WebSite(plan.account_id, plan.primary_domain)
if activation.php_settings is None:
activate_local_site(site)
return None
options = PhpPoolSettings.from_manifest(activation.php_settings)
applied = activate_local_site_with_php(site, options)
return {"php_settings": applied.manifest()}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def update_website_alias(alias_id):
if settings.LOCAL_WEB_ACTIVATION:
jobs = WebsiteAlias.objects.select_related(
"reservation__account"
).exclude(operation=WebsiteAlias.Operation.HTTPS)
run_provisioning_job(
jobs,
alias_id,
apply_website_alias,
"Could not contact the local web node. "
"Check its socket and try again.",
)
def apply_website_alias(job):
alias = queued_website_alias(job)
if job.operation == WebsiteAlias.Operation.REMOVE:
update_local_website_alias(alias, "remove_alias")
with transaction.atomic():
reservation = job.reservation
job.delete()
reservation.delete()
return {}
update_local_website_alias(alias, "apply_alias")
return {"http_active": True}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def enable_website_alias_https(alias_id):
if settings.LOCAL_WEB_ACTIVATION and settings.LOCAL_WEB_HTTPS:
jobs = WebsiteAlias.objects.select_related(
"reservation__account"
).filter(operation=WebsiteAlias.Operation.HTTPS)
run_provisioning_job(
jobs,
alias_id,
apply_alias_https,
"Could not contact the local HTTPS service. "
"Check its socket and try again.",
)
def apply_alias_https(job):
enable_local_https(queued_website_alias(job))
return {"https_active": True}
def queued_website_alias(job):
account = job.reservation.account
if (
job.operation != WebsiteAlias.Operation.REMOVE
and job.primary_domain != account.primary_domain
):
raise ValueError(
"The primary domain changed before the alias request ran."
)
return WebAlias(
WebSite(account.pk, job.primary_domain), job.reservation.domain
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def set_site_php_settings(job_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
SitePhpSettings.objects.select_related("account"),
job_id,
apply_site_php_settings,
"Could not contact the local web node. "
"Check its socket and try again.",
)
def apply_site_php_settings(job):
if job.domain != job.account.primary_domain:
raise ValueError(
"Request PHP settings for the current account domain."
)
site = WebSite(job.account_id, job.domain)
options = PhpPoolSettings.from_manifest(job.requested_settings)
applied = update_local_php_settings(site, options)
return {
"applied_settings": applied.manifest(),
"applied_at": timezone.now(),
}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def measure_site_storage(request_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
SiteStorageUsage.objects.select_related("account"),
request_id,
apply_storage_measurement,
"Could not contact the local web node. "
"Check its socket and try again.",
)
def apply_storage_measurement(request):
if request.domain != request.account.primary_domain:
raise ValueError(
"Request a measurement for the current account domain."
)
used_bytes = measure_local_site_storage(
WebSite(request.account_id, request.domain)
)
return {"used_bytes": used_bytes, "measured_at": timezone.now()}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def set_site_storage_limit(request_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
SiteStorageLimit.objects.select_related("account"),
request_id,
apply_site_storage_limit,
"Could not contact the local web node. "
"Check its socket and try again.",
)
def apply_site_storage_limit(request):
if request.domain != request.account.primary_domain:
raise ValueError(
"Request a storage limit for the current account domain."
)
site = WebSite(request.account_id, request.domain)
set_local_site_storage_limit(site, request.limit_mib)
return {"applied_mib": request.limit_mib, "applied_at": timezone.now()}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def enable_web_https(request_id):
if settings.LOCAL_WEB_HTTPS:
run_provisioning_job(
WebHTTPS.objects.select_related(
"plan__account", "plan__activation"
),
request_id,
apply_web_https,
"Could not contact the local HTTPS service. "
"Check its socket and try again.",
)
def apply_web_https(provisioning):
plan = provisioning.plan
if not plan.can_enable_https:
raise ValueError("Activate the site for the current domain first.")
enable_local_https(WebSite(plan.account_id, plan.primary_domain))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def update_web_sftp(request_id):
if settings.LOCAL_WEB_SFTP:
run_provisioning_job(
SiteSFTP.objects.select_related("account__customer__user"),
request_id,
apply_web_sftp,
"Could not contact the local SFTP service. "
"Check its socket and try again.",
)
def apply_web_sftp(request):
account = request.account
if request.requested_customer_id is not None and (
request.requested_customer_id != account.customer_id
or not account.customer.user.is_active
):
raise ValueError("The customer no longer has access to this account.")
if request.public_keys and (
request.domain != account.primary_domain or not site_is_active(account)
):
raise ValueError("Activate the site for the current domain first.")
site = WebSite(request.account_id, request.domain)
update_local_sftp(SFTPKeys(site, request.public_keys))
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_database(provisioning_id):
if settings.LOCAL_DATABASE_PROVISIONING:
run_provisioning_job(
DatabaseProvisioning.objects.select_related("database"),
provisioning_id,
apply_database_provisioning,
"Could not complete the request to the local MariaDB node. "
"Check its socket and try again.",
)
def apply_database_provisioning(provisioning):
provision_local_database(provisioning.database.spec)
2026-11-21 01:41:06 +01:00
@shared_task(acks_late=True, reject_on_worker_lost=True)
def publish_dns_zone(publication_id):
if settings.LOCAL_DNS_PUBLISHING:
run_provisioning_job(
DnsPublication.objects.all(),
publication_id,
apply_dns_publication,
"Could not complete the request to the local BIND9 node. "
"Check its socket and try again.",
2026-11-21 01:41:06 +01:00
)
def apply_dns_publication(publication):
zone = DnsZone.from_manifest(publication.manifest)
publish_local_zone(zone)
return {"published_serial": zone.serial}
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_mailbox(provisioning_id):
if settings.LOCAL_MAILBOX_PROVISIONING:
run_provisioning_job(
MailboxProvisioning.objects.select_related("mailbox__mail_domain"),
provisioning_id,
apply_mailbox_provisioning,
"Could not complete the request to the local mail node. "
"Check its socket and try again.",
)
def apply_mailbox_provisioning(provisioning):
if provisioning.quota_update:
update_local_mailbox_quota(provisioning.mailbox.spec)
else:
provision_local_mailbox(provisioning.mailbox.spec)
2026-11-21 12:35:24 +01:00
@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.")
if backup.mailboxes is not None and not settings.LOCAL_ACCOUNT_BACKUP_MAIL:
raise ValueError("Enable local mailbox backups before trying again.")
size = create_local_account_backup(
AccountBackupRequest(job.backup_id, backup)
)
return {"archive_bytes": size}
class UnconfirmedArchiveExpirationError(Exception):
pass
@shared_task(acks_late=True, reject_on_worker_lost=True)
def expire_account_backup(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_BACKUP_RETENTION:
try:
run_provisioning_job(
AccountBackupExpiration.objects.select_related("backup"),
job_id,
apply_backup_expiration,
"Could not finish archive expiration.",
lease=ACCOUNT_BACKUP_LEASE,
)
except UnconfirmedArchiveExpirationError:
# The same plan is dispatched again after its lease expires.
return
def apply_backup_expiration(job):
backup = job.backup
request = ArchiveExpirationRequest(
backup.account_id,
backup.backup_id,
tuple(UUID(value) for value in job.keeper_ids),
)
try:
reason = expire_local_account_backup(request)
except (OSError, ValueError):
AccountBackupExpiration.objects.filter(
pk=job.pk, started_at=job.started_at, finished_at__isnull=True
).update(
problem="Could not confirm expiration. The worker will retry."
)
raise UnconfirmedArchiveExpirationError from None
if reason:
raise ValueError(reason)
AccountBackupJob.objects.filter(
pk=backup.pk, expired_at__isnull=True
).update(expired_at=timezone.now())
2026-11-21 12:35:24 +01:00
@shared_task(acks_late=True, reject_on_worker_lost=True)
def restore_website(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS and settings.LOCAL_WEBSITE_RESTORE:
run_provisioning_job(
WebsiteRestoreJob.objects.select_related("backup__account"),
job_id,
apply_website_restore,
UNCONFIRMED_RESTORE,
lease=ACCOUNT_RESTORE_LEASE,
)
def apply_website_restore(job):
account = job.backup.account
site = WebSite(account.pk, account.primary_domain)
if not job.backup.can_restore_website(site):
raise ValueError("The backup no longer matches the current website.")
restore_local_website(
WebsiteRestoreRequest(
job.restore_id,
job.backup.backup_id,
site,
job.filename or None,
job.replace,
)
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def restore_backup_component(job_id):
kinds = enabled_component_restores()
if settings.LOCAL_ACCOUNT_BACKUPS and kinds:
run_provisioning_job(
ComponentRestoreJob.objects.filter(kind__in=kinds).select_related(
"backup__account"
),
job_id,
apply_component_restore,
UNCONFIRMED_RESTORE,
lease=ACCOUNT_RESTORE_LEASE,
)
def apply_component_restore(job):
backup = job.backup
resources = available_restore_resources(
backup, job.kind, current_restore_resources(backup.account, job.kind)
)
target = resources.get(job.resource)
if target is None:
raise ValueError(
"The backup or its restore target is no longer available."
)
restore_local_component(
ComponentRestoreRequest(
job.restore_id, backup.backup_id, backup.account_id, target
)
)
2026-11-21 12:35:24 +01:00
def run_provisioning_job(
jobs, job_id, apply, connection_problem, *, lease=REDISPATCH_AFTER
):
started_at = timezone.now()
pending = jobs.filter(pk=job_id, finished_at__isnull=True)
claim = pending.filter(
2026-11-21 12:35:24 +01:00
Q(started_at__isnull=True) | Q(started_at__lte=started_at - lease)
)
if not claim.update(started_at=started_at):
return
running = pending.filter(started_at=started_at)
job = running.first()
if job is None:
return
problem = ""
2026-11-21 01:41:06 +01:00
updates = {}
try:
2026-11-21 01:41:06 +01:00
updates = apply(job) or {}
except OSError:
problem = connection_problem
except ValueError as error:
problem = str(error)
2026-11-21 01:41:06 +01:00
running.update(finished_at=timezone.now(), problem=problem, **updates)