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

1678 lines
54 KiB
Python

from datetime import datetime, timedelta
from uuid import UUID
from celery import shared_task
from django.conf import settings
from django.db import transaction
from django.db.models import Exists, OuterRef, Q
from django.utils import timezone
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,
)
from coulobre.dns_node import DnsZone
from coulobre.mail_archive_transport import UNCONFIRMED_REMOTE_RESTORE
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 .account_retirement import apply_retirement_job, finalize_retirement
from .backup_restores import (
RestoreKind,
available_restore_resources,
available_website_restore_targets,
current_restore_resources,
enabled_component_restores,
)
from .backup_retention import plan_backup_expirations
from .independent_websites import active_websites, apply_website_operation
from .mail_dns_setup import sync_mail_dns
from .mail_policies import apply_policy, mail_policy_available
from .models import (
AccountBackupExpiration,
AccountBackupJob,
AccountRetirement,
AccountRetirementJob,
AccountServiceJob,
ComponentRestoreJob,
DatabaseLogin,
DatabaseProvisioning,
DnsPublication,
FolderSftpLogin,
HostingAccount,
HostingMailDomain,
IndependentWebsite,
MailboxProvisioning,
MailDeliverySearch,
MailRoutingPublication,
MailVacationPublication,
OffsiteBackupTransfer,
SignInWindow,
SitePhpSettings,
SitePhpVersion,
SiteSFTP,
SiteStorageLimit,
SiteStorageUsage,
SystemBackupJob,
WebActivation,
WebHTTPS,
WebProvisioningPlan,
WebsiteAlias,
WebsiteCertificateJob,
WebsiteRedirectPolicy,
WebsiteRestoreJob,
WebsiteScheduledJob,
)
from .node_client import (
NodeReplyError,
activate_local_site,
create_local_account_backup,
enable_local_https,
expire_local_account_backup,
measure_local_site_storage,
provision_local_database,
provision_local_mailbox,
provision_signing_mailbox,
publish_local_zone,
restore_local_component,
restore_local_website,
set_local_site_storage_limit,
update_local_mailbox_quota,
update_local_php_settings,
update_local_php_version,
update_local_sftp,
update_local_website_alias,
)
from .offsite_backups import (
MAX_ATTEMPTS as MAX_OFFSITE_ATTEMPTS,
)
from .offsite_backups import (
OFFSITE_BACKUP_LEASE,
OFFSITE_BACKUP_QUEUE,
finish_interrupted_transfers,
run_offsite_transfer,
transfer_scope,
)
from .password_reset import send_customer_reset_email
from .php_settings import plan_php_versions
from .resource_requests import lock_hosting_account
from .service_changes import apply_service_change
from .sftp import site_is_active
from .sign_in_limits import current_window
from .website_jobs import (
JOB_QUEUE,
claim_website_job,
due_website_jobs,
recover_interrupted_runs,
run_website_job,
save_website_job_result,
)
from .website_jobs import (
Result as WebsiteJobResult,
)
REDISPATCH_AFTER = timedelta(minutes=5)
ACCOUNT_BACKUP_LEASE = timedelta(seconds=BACKUP_TIMEOUT_SECONDS + 60)
ACCOUNT_RESTORE_LEASE = timedelta(seconds=RESTORE_TIMEOUT_SECONDS + 60)
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"
DNS_PUBLISHING_QUEUE = "coulobre-dns-publishing"
MAILBOX_PROVISIONING_QUEUE = "coulobre-mailbox-provisioning"
@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)
)
.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
)
plan = pending.first()
if plan is None:
return
apache_config = WebSite(plan.account_id, plan.primary_domain).render(
"apache"
)
pending.update(apache_config=apache_config, completed_at=timezone.now())
@shared_task
def dispatch_web_activations():
if settings.LOCAL_WEB_ACTIVATION:
dispatch_provisioning_jobs(
WebsiteRedirectPolicy,
deploy_website_redirects,
WEB_ACTIVATION_QUEUE,
)
dispatch_provisioning_jobs(
IndependentWebsite,
provision_independent_website,
WEB_ACTIVATION_QUEUE,
condition=~Q(operation=IndependentWebsite.Operation.HTTPS),
)
dispatch_provisioning_jobs(
WebActivation, activate_web_plan, WEB_ACTIVATION_QUEUE
)
active_primary = WebActivation.objects.filter(
plan__account_id=OuterRef("reservation__account_id"),
plan__primary_domain=OuterRef("primary_domain"),
finished_at__isnull=False,
problem="",
)
dispatch_provisioning_jobs(
WebsiteAlias,
update_website_alias,
WEB_ACTIVATION_QUEUE,
condition=Q(wait_for_website=False) | Exists(active_primary),
operation__in=(
WebsiteAlias.Operation.ACTIVATE,
WebsiteAlias.Operation.REMOVE,
),
)
dispatch_provisioning_jobs(
SitePhpSettings, set_site_php_settings, WEB_ACTIVATION_QUEUE
)
dispatch_provisioning_jobs(
SitePhpVersion, set_site_php_version, 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():
from .certificate_uploads import UPLOAD_LIFETIME
WebsiteCertificateJob.objects.filter(
requested_at__lte=timezone.now() - timedelta(seconds=UPLOAD_LIFETIME)
).exclude(encrypted_upload="").update(encrypted_upload="")
if settings.LOCAL_WEB_HTTPS:
dispatch_provisioning_jobs(
WebsiteCertificateJob, apply_certificate_job, WEB_HTTPS_QUEUE
)
dispatch_provisioning_jobs(
IndependentWebsite,
provision_independent_website,
WEB_HTTPS_QUEUE,
operation=IndependentWebsite.Operation.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:
if settings.LOCAL_FOLDER_SFTP:
dispatch_provisioning_jobs(
FolderSftpLogin, apply_folder_sftp_job, WEB_SFTP_QUEUE
)
dispatch_provisioning_jobs(SiteSFTP, update_web_sftp, WEB_SFTP_QUEUE)
@shared_task
def dispatch_database_provisioning():
if settings.LOCAL_DATABASE_PROVISIONING:
dispatch_provisioning_jobs(
DatabaseLogin,
provision_database_login,
DATABASE_PROVISIONING_QUEUE,
)
dispatch_provisioning_jobs(
DatabaseProvisioning,
provision_database,
DATABASE_PROVISIONING_QUEUE,
)
@shared_task
def dispatch_dns_publications():
if settings.LOCAL_DNS_PUBLISHING:
if settings.MANAGE_MAIL_DNS:
domains = HostingMailDomain.objects.filter(
dns_sync_requested=True,
account__services_suspended=False,
account__retired_at__isnull=True,
).order_by("pk")[:100]
for mail_domain in domains:
sync_mail_dns(mail_domain)
dispatch_provisioning_jobs(
DnsPublication, publish_dns_zone, DNS_PUBLISHING_QUEUE
)
@shared_task
def dispatch_mailbox_provisioning():
MailDeliverySearch.objects.filter(expires_at__lte=timezone.now()).delete()
if settings.LOCAL_MAILBOX_PROVISIONING:
dispatch_provisioning_jobs(
MailDeliverySearch,
search_mail_delivery,
MAILBOX_PROVISIONING_QUEUE,
expires_at__gt=timezone.now(),
)
dispatch_provisioning_jobs(
MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE
)
if mail_policy_available("routing"):
dispatch_provisioning_jobs(
MailRoutingPublication,
publish_mail_routing,
MAILBOX_PROVISIONING_QUEUE,
)
if mail_policy_available("vacation"):
dispatch_provisioning_jobs(
MailVacationPublication,
publish_mail_vacation,
MAILBOX_PROVISIONING_QUEUE,
)
@shared_task
def dispatch_account_service_changes():
queues = {
AccountServiceJob.Kind.WEB: WEB_ACTIVATION_QUEUE,
AccountServiceJob.Kind.SFTP: WEB_SFTP_QUEUE,
AccountServiceJob.Kind.DATABASE: DATABASE_PROVISIONING_QUEUE,
AccountServiceJob.Kind.MAILBOX: MAILBOX_PROVISIONING_QUEUE,
}
for kind, queue in queues.items():
dispatch_provisioning_jobs(
AccountServiceJob, change_service_access, queue, kind=kind
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def change_service_access(job_id):
run_provisioning_job(
AccountServiceJob.objects.select_related("change"),
job_id,
apply_service_change,
"Could not confirm the service change. Check the node and retry.",
)
@shared_task
def dispatch_account_retirements():
kind = AccountRetirementJob.Kind
queues = {
kind.ALIAS: WEB_ACTIVATION_QUEUE,
kind.DATABASE: DATABASE_PROVISIONING_QUEUE,
kind.MAILBOX: MAILBOX_PROVISIONING_QUEUE,
kind.DNS: DNS_PUBLISHING_QUEUE,
}
for service, queue in queues.items():
dispatch_provisioning_jobs(
AccountRetirementJob, retire_account_resource, queue, kind=service
)
aliases = AccountRetirementJob.objects.filter(
retirement_id=OuterRef("retirement_id"), kind=kind.ALIAS
).filter(Q(finished_at__isnull=True) | ~Q(problem=""))
dispatch_provisioning_jobs(
AccountRetirementJob,
retire_account_resource,
WEB_ACTIVATION_QUEUE,
kind=kind.WEB,
condition=~Exists(aliases),
)
unfinished = AccountRetirementJob.objects.filter(
retirement_id=OuterRef("pk")
).filter(Q(finished_at__isnull=True) | ~Q(problem=""))
releasable = (
AccountRetirement.objects.filter(
policy=AccountRetirement.Policy.RELEASE, released_at__isnull=True
)
.filter(~Exists(unfinished))
.values_list("account_id", flat=True)
)
for account_id in releasable[:100]:
finalize_retirement(account_id)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def retire_account_resource(job_id):
kind = AccountRetirementJob.Kind
aliases = AccountRetirementJob.objects.filter(
retirement_id=OuterRef("retirement_id"), kind=kind.ALIAS
).filter(Q(finished_at__isnull=True) | ~Q(problem=""))
jobs = AccountRetirementJob.objects.filter(
~Q(kind=kind.WEB) | ~Exists(aliases)
)
run_provisioning_job(
jobs,
job_id,
apply_retirement_job,
"Could not confirm the cleanup on the node. Check the node and retry.",
)
@shared_task
def dispatch_account_backups():
if settings.LOCAL_ACCOUNT_BACKUPS:
queue_due_account_backups(timezone.now())
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())
@shared_task
def dispatch_offsite_backups():
if settings.LOCAL_ACCOUNT_BACKUPS and settings.OFFSITE_BACKUP_DESTINATIONS:
now = timezone.now()
finish_interrupted_transfers(now)
dispatch_provisioning_jobs(
OffsiteBackupTransfer,
transfer_offsite_backup,
OFFSITE_BACKUP_QUEUE,
lease=OFFSITE_BACKUP_LEASE,
attempts__lt=MAX_OFFSITE_ATTEMPTS,
**transfer_scope(now),
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def transfer_offsite_backup(job_id):
if settings.LOCAL_ACCOUNT_BACKUPS and settings.OFFSITE_BACKUP_DESTINATIONS:
run_offsite_transfer(job_id)
def dispatch_provisioning_jobs(
model, task, queue, *, lease=REDISPATCH_AFTER, condition=None, **scope
):
now = timezone.now()
stale_before = now - REDISPATCH_AFTER
waiting = model.objects.filter(finished_at__isnull=True, **scope)
if condition is not None:
waiting = waiting.filter(condition)
pending = (
waiting.filter(
Q(last_dispatched_at__isnull=True)
| Q(last_dispatched_at__lte=stale_before)
)
.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__hosting_plan"
),
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)
options = (
PhpPoolSettings.from_manifest(activation.php_settings)
if activation.php_settings is not None
else PhpPoolSettings()
)
starter = {"starter_page": True} if activation.starter_page else {}
applied, version = activate_local_site(
site, options, plan_php_versions(plan.account), **starter
)
return {"php_settings": applied.manifest(), "applied_php_version": version}
@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 set_site_php_version(job_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
SitePhpVersion.objects.select_related("account__hosting_plan"),
job_id,
apply_site_php_version,
"Could not confirm the PHP change on the web node. "
"Retry the request.",
)
def apply_site_php_version(job):
account = job.account
if account.retired_at or account.services_suspended:
raise ValueError("The hosting account is suspended or retired.")
if job.domain != account.primary_domain or not site_is_active(account):
raise ValueError("Activate the current website before changing PHP.")
versions = plan_php_versions(account)
if versions and job.requested_version not in versions:
raise ValueError("The hosting plan no longer allows this PHP series.")
site = WebSite(job.account_id, job.domain)
return {
"applied_version": update_local_php_version(
site, job.requested_version
)
}
@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)
@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 BIND9 node. "
"Check the node connection and try again.",
)
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 mail node. "
"Check the node connection and try again.",
)
def apply_mailbox_provisioning(provisioning):
if provisioning.quota_update:
update_local_mailbox_quota(provisioning.mailbox.spec)
elif settings.MANAGE_MAIL_DNS or settings.MAIL_NODE_DKIM:
public_key = provision_signing_mailbox(provisioning.mailbox.spec)
domain = provisioning.mailbox.mail_domain
if settings.MANAGE_MAIL_DNS:
sync_mail_dns(domain, public_key=public_key)
else:
HostingMailDomain.objects.filter(pk=domain.pk).update(
dkim_record=public_key
)
else:
provision_local_mailbox(provisioning.mailbox.spec)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def publish_mail_routing(job_id):
if mail_policy_available("routing"):
run_provisioning_job(
MailRoutingPublication.objects.select_related(
"mail_domain__account__hosting_plan"
),
job_id,
apply_mail_routing_job,
"Could not reach the mail node to apply routing. Try again.",
)
def apply_mail_routing_job(job):
return apply_policy(job, job.mail_domain)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def publish_mail_vacation(job_id):
if mail_policy_available("vacation"):
run_provisioning_job(
MailVacationPublication.objects.select_related(
"mailbox__mail_domain__account"
),
job_id,
apply_mail_vacation_job,
"Could not reach the mail node to apply replies. Try again.",
)
def apply_mail_vacation_job(job):
return apply_policy(job, job.mailbox)
@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.select_related("account"),
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):
if job.export_customer_id is None:
return create_backup_job_archive(job)
with transaction.atomic():
try:
job.account = lock_hosting_account(
job.account_id, job.export_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account's customer assignment changed."
) from None
if job.account.retired_at is not None:
raise ValueError("The hosting account is retired.")
return create_backup_job_archive(job)
def create_backup_job_archive(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.")
current_sites = {website.spec for website in active_websites(job.account)}
if set(backup.additional_websites) - current_sites:
raise ValueError(
"An additional website is no longer available for backup."
)
if backup.mailboxes is not None:
if job.remote_mail:
if not settings.REMOTE_ACCOUNT_BACKUP_MAIL:
raise ValueError(
"Enable remote mailbox backups before trying again."
)
current = current_restore_resources(
job.account, RestoreKind.MAILBOX
)
if any(
mailbox.address not in current for mailbox in backup.mailboxes
):
raise ValueError(
"A mailbox no longer belongs to this account."
)
elif 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,
remote_mail=job.remote_mail,
publish_to_customer=job.export_customer_id is not None,
database_suffix=job.export_database_suffix,
)
)
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())
@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 with_customer_restore_scope(job, apply):
customer_id = job.requested_customer_id
if customer_id is None:
return apply(job)
with transaction.atomic():
try:
account = lock_hosting_account(job.backup.account_id, customer_id)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account assignment changed."
) from None
if account.retired_at is not None:
raise ValueError("The hosting account is retired.")
job.backup.account = account
return apply(job)
def apply_website_restore(job):
return with_customer_restore_scope(job, restore_website_target)
def restore_website_target(job):
account = job.backup.account
site = (
WebSite.from_manifest(job.site_manifest)
if job.site_manifest is not None
else WebSite(account.pk, account.primary_domain)
)
if (
available_website_restore_targets(job.backup).get(site.node_key)
!= 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):
return with_customer_restore_scope(job, restore_component_target)
def restore_component_target(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."
)
if job.kind == RestoreKind.MAILBOX:
enabled = (
settings.REMOTE_MAILBOX_RESTORE
if job.remote_mail
else settings.LOCAL_MAILBOX_RESTORE
)
if not enabled:
raise ValueError(
"Re-enable the requested mailbox restore transport."
)
try:
restore_local_component(
ComponentRestoreRequest(
job.restore_id,
backup.backup_id,
backup.account_id,
target,
remote_mail=job.remote_mail,
)
)
except (OSError, NodeReplyError):
if job.remote_mail:
raise ValueError(UNCONFIRMED_REMOTE_RESTORE) from None
raise
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(
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 = ""
updates = {}
try:
updates = apply(job) or {}
except OSError:
problem = connection_problem
except ValueError as error:
problem = str(error)
running.update(finished_at=timezone.now(), problem=problem, **updates)
@shared_task
def expire_sign_in_windows():
SignInWindow.objects.filter(slot__lt=current_window() - 1).delete()
@shared_task
def send_panel_invitation(invitation_id, revision):
from .invitations import deliver_invitation
deliver_invitation(invitation_id, revision)
@shared_task
def send_customer_password_reset(email):
send_customer_reset_email(email)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_independent_website(job_id):
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
IndependentWebsite.objects.select_related(
"reservation__account__hosting_plan"
),
job_id,
apply_website_operation,
"Could not complete the request to the web node. Try again.",
)
@shared_task
def dispatch_website_jobs():
if not settings.WEBSITE_JOBS:
return
now = timezone.now()
recover_interrupted_runs(now)
due = due_website_jobs(now).values_list("pk", "account_id", "next_run_at")
for job_id, account_id, next_run in list(due[:100]):
execute_website_job.apply_async(
args=[account_id, job_id, next_run.isoformat()],
queue=JOB_QUEUE,
expires=90,
retry=False,
)
WebsiteScheduledJob.objects.filter(
pk=job_id, next_run_at=next_run
).update(dispatched_at=now)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def execute_website_job(account_id, job_id, scheduled_for):
if not settings.WEBSITE_JOBS:
return
request = claim_website_job(
account_id, job_id, datetime.fromisoformat(scheduled_for)
)
if request is None:
return
try:
result, code = run_website_job(request)
except (OSError, NodeReplyError):
result, code = WebsiteJobResult.UNCONFIRMED, None
except ValueError:
result, code = WebsiteJobResult.FAILED, None
save_website_job_result(job_id, request.run_id, result, code)
@shared_task(queue="coulobre-mailbox-provisioning")
def refresh_mail_queue(domain_id, requested_at):
from coulobre.mail_queue import QUEUE_NAMES, MailQueueRequest
from .node_client import apply_on_local_node
domain = HostingMailDomain.objects.filter(
pk=domain_id,
account__retired_at__isnull=True,
queue_requested_at=requested_at,
).first()
if domain is None or not settings.LOCAL_MAILBOX_PROVISIONING:
return
try:
report = apply_on_local_node(
MailQueueRequest(domain.domain, detailed=True),
"/run/coulobre-mail-apply.sock",
"mail node",
"queue summary",
timeout=20,
)
counts = report["counts"]
if (
set(counts) != set(QUEUE_NAMES)
or any(
type(value) is not int or not 0 <= value <= 20000
for value in counts.values()
)
or type(report["partial"]) is not bool
):
raise ValueError
snapshot = {
"counts": counts,
"partial": report["partial"],
"entries": report.get("entries", []),
}
except (KeyError, TypeError, ValueError, OSError):
snapshot = {"error": "Could not read the queue from the mail node."}
HostingMailDomain.objects.filter(
pk=domain_id, queue_requested_at=requested_at
).update(
queue_report=snapshot,
queue_observed_at=timezone.now(),
)
@shared_task(queue="coulobre-web-activation")
def collect_website_usage(snapshot_id, requested_at):
from .models import WebsiteUsage
from .node_client import apply_on_local_node
if not settings.WEBSITE_USAGE:
return
snapshot = (
WebsiteUsage.objects.select_related("account")
.filter(
pk=snapshot_id,
requested_at=requested_at,
account__retired_at__isnull=True,
)
.first()
)
if snapshot is None:
return
try:
if snapshot.node_key == str(snapshot.account_id):
if snapshot.account.primary_domain != snapshot.domain:
return
site = WebSite(snapshot.account_id, snapshot.domain)
else:
website = (
active_websites(snapshot.account)
.filter(
pk=int(snapshot.node_key.removeprefix("s")),
domain=snapshot.domain,
)
.first()
)
if website is None:
return
site = website.spec
response = apply_on_local_node(
site,
"/run/coulobre-website-usage.sock",
"web node",
"website usage",
timeout=20,
)
report = {
name: response[name]
for name in (
"month",
"storage_bytes",
"traffic_bytes",
"access_lines",
"error_lines",
"partial",
)
}
datetime.strptime(report["month"], "%Y-%m")
for field in ("storage_bytes", "traffic_bytes"):
size = report[field]
if (field != "traffic_bytes" or size is not None) and (
type(size) is not int or not 0 <= size < 2**63
):
raise ValueError
for field in ("access_lines", "error_lines"):
lines = report[field]
if (
not isinstance(lines, list)
or len(lines) > 8
or any(
not isinstance(line, str) or len(line) > 256
for line in lines
)
):
raise ValueError
if type(report["partial"]) is not bool:
raise ValueError
except (KeyError, TypeError, ValueError, OSError):
report = {"error": "Could not measure usage on the web node."}
WebsiteUsage.objects.filter(
pk=snapshot.pk, requested_at=requested_at
).update(
report=report,
observed_at=timezone.now(),
)
@shared_task(queue="coulobre-mailbox-provisioning")
def collect_mailbox_usage(mailbox_id, requested_at):
from coulobre.mail_node import MailboxUsageRequest
from .models import HostingMailbox
from .node_client import apply_on_local_node
if not settings.LOCAL_MAILBOX_PROVISIONING or not settings.WEBSITE_USAGE:
return
mailboxes = HostingMailbox.objects.filter(
pk=mailbox_id,
usage_requested_at=requested_at,
mail_domain__account__retired_at__isnull=True,
)
mailbox = mailboxes.select_related("mail_domain").first()
if mailbox is None:
return
try:
reply = apply_on_local_node(
MailboxUsageRequest(mailbox.spec),
"/run/coulobre-mail-apply.sock",
"mail node",
"mailbox quota usage",
timeout=15,
)
used = reply["usage_bytes"]
if type(used) is not int or not 0 <= used < 2**63:
raise ValueError
except (KeyError, OSError, ValueError):
used = None
mailboxes.update(usage_bytes=used, usage_observed_at=timezone.now())
@shared_task(queue="coulobre-operator-actions")
def run_operator_operation(job_id):
from coulobre.http_defaults import HttpDefaultsRequest
from coulobre.operator_node import SOCKET, OperatorRequest
from .models import OperatorOperation
from .node_client import apply_on_local_node
def apply(job):
spec = (
HttpDefaultsRequest(job.target, job.parameters)
if job.action == "http-defaults"
else OperatorRequest(job.action, job.target, job.plan)
)
result = apply_on_local_node(
spec, SOCKET, "operator service", "host operation", timeout=32 * 60
)
for key in (*spec.manifest(), "state", "problem"):
result.pop(key, None)
return {"result": result}
run_provisioning_job(
OperatorOperation.objects.all(),
job_id,
apply,
"The operator service did not report a result. "
"Check the service journal.",
lease=timedelta(minutes=35),
)
@shared_task(queue="coulobre-mailbox-provisioning")
def run_mail_queue_operation(job_id):
from coulobre.mail_queue import MailQueueAction
from .models import MailQueueOperation
from .node_client import apply_on_local_node
def apply(job):
if (
not settings.LOCAL_MAILBOX_PROVISIONING
or job.domain.account.retired_at is not None
):
raise ValueError("The mail domain is no longer available.")
request = MailQueueAction(
job.domain.domain, job.queue_id, job.arrival, job.action
)
apply_on_local_node(
request,
"/run/coulobre-mail-apply.sock",
"mail node",
"queue action",
timeout=60,
)
run_provisioning_job(
MailQueueOperation.objects.select_related("domain__account"),
job_id,
apply,
"The mail node did not confirm the queue action.",
lease=timedelta(minutes=3),
)
@shared_task(queue=MAILBOX_PROVISIONING_QUEUE)
def search_mail_delivery(job_id):
from datetime import UTC, datetime
from coulobre.mail_delivery import MAX_RESULTS, MailDeliveryRequest
from .domain_policies import policy_for
from .node_client import apply_on_local_node
def apply(job):
domain = job.domain
expected = job.customer_id_at_request
if (
(expected is not None and domain.account.customer_id != expected)
or domain.account.retired_at is not None
or job.expires_at <= timezone.now()
or not policy_for(domain.account, domain.domain).mail_managed
):
raise ValueError("This mail domain is no longer available.")
spec = MailDeliveryRequest.from_manifest(job.filters)
if spec.domain != domain.domain:
raise ValueError("This mail domain is no longer available.")
reply = apply_on_local_node(
spec,
"/run/coulobre-mail-apply.sock",
"mail node",
"delivery search",
timeout=30,
)
events = reply.get("events")
if not isinstance(events, list) or len(events) > MAX_RESULTS:
raise ValueError(
"The mail node returned an invalid delivery report."
)
for event in events:
timestamp = (
event.get("timestamp") if isinstance(event, dict) else None
)
if (
type(timestamp) is not int
or not spec.start <= timestamp <= spec.end
):
raise ValueError(
"The mail node returned an invalid delivery timestamp."
)
event["timestamp"] = datetime.fromtimestamp(
timestamp, UTC
).strftime("%Y-%m-%d %H:%M:%S")
return {
"report": {
"events": events,
"partial": reply.get("partial") is True,
}
}
if settings.LOCAL_MAILBOX_PROVISIONING:
run_provisioning_job(
MailDeliverySearch.objects.select_related("domain__account"),
job_id,
apply,
"The mail node did not return a delivery report.",
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def apply_certificate_job(job_id):
from django.views.decorators.debug import sensitive_variables
from coulobre.web_certificates import WebCertificateRequest
from .certificate_uploads import open_upload
from .certificate_views import account_certificate_sites
from .node_client import apply_on_local_node
@sensitive_variables()
def apply(job):
site = WebSite.from_manifest(job.site)
with transaction.atomic():
try:
account = lock_hosting_account(
job.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"This hosting account is no longer available."
) from None
if (
account.services_suspended
or account.retired_at is not None
or account_certificate_sites(account).get(site.domain) != site
):
raise ValueError("This website is no longer active.")
spec = WebCertificateRequest(
site,
job.action,
*(open_upload(job) if job.action == "upload" else ()),
**job.acme,
)
reply = apply_on_local_node(
spec,
"/run/coulobre-https-apply.sock",
"web node",
"certificate operation",
identity=spec.identity(),
)
certificate = reply.get("certificate")
if (
not isinstance(certificate, dict)
or type(certificate.get("installed")) is not bool
):
raise ValueError("The web node did not return certificate status.")
return {"certificate": certificate}
if settings.LOCAL_WEB_HTTPS:
run_provisioning_job(
WebsiteCertificateJob.objects.all(),
job_id,
apply,
"The HTTPS worker did not confirm the certificate operation.",
)
WebsiteCertificateJob.objects.filter(
pk=job_id, finished_at__isnull=False
).exclude(encrypted_upload="").update(encrypted_upload="")
@shared_task(acks_late=True, reject_on_worker_lost=True)
def deploy_website_redirects(job_id):
from coulobre.web_redirects import OPERATION, RedirectConfiguration
from .node_client import apply_on_local_node
from .redirect_views import hosted_redirect_targets
def apply(job):
with transaction.atomic():
try:
account = lock_hosting_account(
job.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account is no longer available."
) from None
request = RedirectConfiguration.from_manifest(
{
"operation": OPERATION,
"website": job.website,
"rules": job.requested_rules,
}
)
if (
account.retired_at is not None
or account.services_suspended
or hosted_redirect_targets(account).get(job.domain)
!= request.website
):
raise ValueError("The website is no longer available.")
apply_on_local_node(
request,
"/run/coulobre-web-apply.sock",
"web node",
"redirect update",
)
return {"applied_rules": job.requested_rules}
if settings.LOCAL_WEB_ACTIVATION:
run_provisioning_job(
WebsiteRedirectPolicy.objects.all(),
job_id,
apply,
"The web node did not confirm the website redirect update.",
)
@shared_task(acks_late=True, reject_on_worker_lost=True)
def provision_database_login(job_id):
from coulobre.database_login import DatabaseLoginRequest
from .node_client import apply_on_local_node
def apply(job):
with transaction.atomic():
try:
account = lock_hosting_account(
job.database.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account is no longer available."
) from None
if account.retired_at is not None or account.services_suspended:
raise ValueError("The hosting account is inactive.")
spec = DatabaseLoginRequest(job.spec, job.access, job.action)
apply_on_local_node(
spec,
"/run/coulobre-database-apply.sock",
"MariaDB node",
"database login",
)
return {}
if settings.LOCAL_DATABASE_PROVISIONING:
run_provisioning_job(
DatabaseLogin.objects.select_related("database"),
job_id,
apply,
"The MariaDB node did not confirm the login operation.",
)
DatabaseLogin.objects.filter(
pk=job_id, action="remove", problem="", finished_at__isnull=False
).delete()
@shared_task(acks_late=True, reject_on_worker_lost=True)
def apply_folder_sftp_job(job_id):
from coulobre.folder_sftp import FOLDER_SOCKET
from .node_client import apply_on_local_node
def apply(job):
with transaction.atomic():
try:
account = lock_hosting_account(
job.account_id, job.requested_customer_id
)
except HostingAccount.DoesNotExist:
raise ValueError(
"The hosting account is no longer available."
) from None
if (
account.retired_at is not None
or account.primary_domain != job.domain
or (account.services_suspended and job.action != "remove")
):
raise ValueError("The hosting account is inactive.")
spec = job.spec
apply_on_local_node(
spec,
FOLDER_SOCKET,
"web node",
"folder SFTP login",
identity=spec.identity(),
)
return {}
if settings.LOCAL_FOLDER_SFTP:
run_provisioning_job(
FolderSftpLogin.objects.all(),
job_id,
apply,
"The hosting node did not confirm the folder SFTP operation.",
)
FolderSftpLogin.objects.filter(
pk=job_id, action="remove", problem="", finished_at__isnull=False
).delete()
@shared_task
def dispatch_system_backups():
from .system_backup_views import queue_scheduled_system_backup
if settings.SYSTEM_BACKUPS:
queue_scheduled_system_backup(timezone.now())
dispatch_provisioning_jobs(
SystemBackupJob,
run_system_backup,
"coulobre-operator-actions",
lease=timedelta(minutes=35),
)
@shared_task(
queue="coulobre-operator-actions",
acks_late=True,
reject_on_worker_lost=True,
)
def run_system_backup(job_id):
from coulobre.operator_node import SOCKET, OperatorRequest
from .node_client import apply_on_local_node
def apply(job):
reply = apply_on_local_node(
OperatorRequest("system-backup", target=str(job.identifier)),
SOCKET,
"operator service",
"system backup",
timeout=32 * 60,
)
fields = ("archive", "bytes", "sha256", "created_at")
return {"report": {key: reply[key] for key in fields if key in reply}}
if settings.SYSTEM_BACKUPS:
run_provisioning_job(
SystemBackupJob.objects.all(),
job_id,
apply,
"The operator service did not confirm the system backup.",
lease=timedelta(minutes=35),
)