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

324 lines
9.9 KiB
Python
Raw Normal View History

2026-11-19 21:18:37 +01:00
from datetime import timedelta
from celery import shared_task
from django.conf import settings
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,
)
2026-11-21 01:41:06 +01:00
from coulobre.dns_node import DnsZone
from coulobre.sftp_keys import SFTPKeys
from coulobre.web_node import WebSite
2026-11-21 01:41:06 +01:00
from .models import (
2026-11-21 12:35:24 +01:00
AccountBackupJob,
2026-11-21 01:41:06 +01:00
DatabaseProvisioning,
DnsPublication,
MailboxProvisioning,
SiteSFTP,
2026-11-21 01:41:06 +01:00
WebActivation,
WebHTTPS,
2026-11-21 01:41:06 +01:00
WebProvisioningPlan,
)
from .node_client import (
activate_local_site,
2026-11-21 12:35:24 +01:00
create_local_account_backup,
enable_local_https,
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,
update_local_sftp,
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_BACKUP_QUEUE = "coulobre-account-backups"
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
)
@shared_task
def dispatch_web_https():
if settings.LOCAL_WEB_HTTPS:
dispatch_provisioning_jobs(WebHTTPS, enable_web_https, WEB_HTTPS_QUEUE)
@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:
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)
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."
)
activate_local_site(WebSite(plan.account_id, plan.primary_domain))
@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):
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.")
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()
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)