diff --git a/docs/deployment.md b/docs/deployment.md index 8be31ba..a0e93c8 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -225,6 +225,7 @@ peer configuration above so Apache supplies the visitor address. Keep the Gunicorn socket private to the panel service and the front-end server. A direct TCP connection uses its network peer address for rate limiting. + ## Protect a host with nftables and Fail2ban Enable protection independently on a panel, web, mail, or DNS host. Use the @@ -636,6 +637,43 @@ serves no tenant content when unknown hosts should be rejected. [Apache default virtual host](https://httpd.apache.org/docs/current/en/vhosts/name-based.html#defaultvhost) · [Deleting a Certbot certificate](https://eff-certbot.readthedocs.io/en/stable/using.html#deleting-certificates) +## Host independent websites + +Set a hosting plan's **Website limit** above one to allow additional +websites under an account. The limit includes the primary website. Existing +plans start with one website. In **Independent websites**, choose **Add +website** to provision a domain or subdomain with its own document root, +operating-system user, PHP-FPM pool, and Apache virtual host. + +Leave the PHP series blank to select the newest installed stable series +allowed by the plan. Changing the series on one website keeps the other +websites on their configured versions. If the plan sets a website storage +limit, the web node applies that quota to the new site's user. + +Point the domain's DNS at the web server and select **Enable HTTPS** after +setting up the existing Certbot worker. Each website has its own Certbot +lineage. An alias under **Website aliases** shares the primary document +root and runtime. + +Use **Suspend website** to disable access to a single site. Account-wide +suspension applies to all its active websites. Resuming the account preserves +any independent website suspension. To retire a site, suspend it and +confirm its domain using **Retire website**. The web node archives its data +and disables its Apache and PHP configuration. Retiring a failed provisioning request also frees its place in the plan. +Its domain remains reserved until released with the account's names. + +Operators can download the website's version 2 manifest. Use the existing +[website SFTP setup](development.md#install-sftp-keys-on-a-web-node) on the web node +with that manifest to authorize a key for the site's own user. The web +node suspends new SFTP logins for a suspended independent website when +keys have been installed. + +New account archives include the primary website and activated independent +websites. Select the website when restoring a file or document root from +an archive containing several sites. The archive identifies each website +by domain and site ID. Upgrade the panel and its web and backup workers +together before enabling additional sites. + ## Enable HTTPS for hosted websites Once a site is active, obtain the website certificate with Certbot on the diff --git a/docs/development.md b/docs/development.md index 72c81c9..9812bb4 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1215,12 +1215,14 @@ time. Use the [website backup command](#back-up-and-restore-hosted-website-files) on the web node and the [database backup command](#back-up-and-restore-a-managed-database) on each database node. Transfer the resulting files to a root-controlled -directory with mode `0600` on every archive. Name the website archive +directory with mode `0600` on every archive. Name the primary website archive `website.tar.gz` and each SQL dump `database-.sql.gz`, for example `database-cms.sql.gz`. When the manifest includes mail, use the [mailbox backup command](#back-up-and-restore-a-mailbox) on the mail node and place each archive under `mailboxes//.tar.gz` within the -component directory. Assemble the ZIP with the same account manifest. +component directory. For a version 3 account manifest, use +`websites/s.tar.gz` for each entry in `additional_websites`. +Assemble the ZIP with the same account manifest. ```sh sudo /opt/coulobre/bin/coulobre-account-backup pack \ @@ -1244,6 +1246,8 @@ sudo /opt/coulobre/bin/coulobre-account-backup unpack \ ``` Use the recovered `website.json` and `website.tar.gz` with `restore-site`. +For an independent website, use its `websites/s.json` and +`websites/s.tar.gz` pair with the same command. Use each `database-.json` and `database-.sql.gz` pair with `restore-database`. For mail, use the original manifest and archive recovered as `mailboxes//.json` and diff --git a/src/coulobre/account_backup.py b/src/coulobre/account_backup.py index 26a144c..be1f78f 100644 --- a/src/coulobre/account_backup.py +++ b/src/coulobre/account_backup.py @@ -18,6 +18,7 @@ from .web_node import WebSite BASE_MANIFEST_VERSION = 1 MAIL_MANIFEST_VERSION = 2 +MULTI_SITE_MANIFEST_VERSION = 3 MANIFEST_KIND = "coulobre_account_backup" MANIFEST_NAME = "manifest.json" MAX_MANIFEST_BYTES = 1024 * 1024 @@ -29,8 +30,27 @@ class AccountBackup: website: WebSite databases: tuple[DatabaseSpec, ...] mailboxes: tuple[MailboxSpec, ...] | None = None + additional_websites: tuple[WebSite, ...] = () def __post_init__(self): + if self.website.site_id is not None: + raise ValueError( + "The primary website must use its account identity." + ) + sites = {self.website.domain} + site_ids = set() + for site in self.additional_websites: + if ( + site.account_id != self.website.account_id + or site.site_id is None + ): + raise ValueError( + "All websites must belong to the backup account." + ) + if site.domain in sites or site.site_id in site_ids: + raise ValueError("The account backup lists a website twice.") + sites.add(site.domain) + site_ids.add(site.site_id) names = set() for database in self.databases: if database.account_id != self.website.account_id: @@ -57,6 +77,11 @@ class AccountBackup: manifest["mailboxes"] = [ mailbox.manifest() for mailbox in self.mailboxes ] + if self.additional_websites: + manifest["version"] = MULTI_SITE_MANIFEST_VERSION + manifest["additional_websites"] = [ + site.manifest() for site in self.additional_websites + ] return manifest @classmethod @@ -67,30 +92,44 @@ class AccountBackup: if type(version) is not int or version not in ( BASE_MANIFEST_VERSION, MAIL_MANIFEST_VERSION, + MULTI_SITE_MANIFEST_VERSION, ): raise ValueError("Unsupported account backup manifest version.") fields = {"version", "kind", "website", "databases"} - if version == MAIL_MANIFEST_VERSION: + if version == MULTI_SITE_MANIFEST_VERSION: + fields.add("additional_websites") + if version == MAIL_MANIFEST_VERSION or ( + version == MULTI_SITE_MANIFEST_VERSION and "mailboxes" in data + ): fields.add("mailboxes") if data.keys() != fields or not isinstance(data["databases"], list): raise ValueError("Expected a Coulobre account backup manifest.") mailboxes = None - if version == MAIL_MANIFEST_VERSION: + if "mailboxes" in fields: if not isinstance(data["mailboxes"], list): raise ValueError("Expected a list of mailbox manifests.") mailboxes = tuple( MailboxSpec.from_manifest(item) for item in data["mailboxes"] ) + sites = data.get("additional_websites", []) + if not isinstance(sites, list): + raise ValueError( + "Expected a list of additional website manifests." + ) return cls( WebSite.from_manifest(data["website"]), tuple( DatabaseSpec.from_manifest(item) for item in data["databases"] ), mailboxes, + tuple(WebSite.from_manifest(site) for site in sites), ) def components(self): yield self.website, "website.json", "website.tar.gz" + for site in self.additional_websites: + name = f"websites/{site.node_key}" + yield site, f"{name}.json", f"{name}.tar.gz" for database in self.databases: name = f"database-{database.suffix}" yield database, f"{name}.json", f"{name}.sql.gz" diff --git a/src/coulobre/hosting/account_backup_forms.py b/src/coulobre/hosting/account_backup_forms.py index 6032564..7257a0b 100644 --- a/src/coulobre/hosting/account_backup_forms.py +++ b/src/coulobre/hosting/account_backup_forms.py @@ -91,6 +91,18 @@ class WebsiteRestoreForm(BackupRestoreForm): label="Replace the existing file at this path", required=False ) + def __init__(self, *args, targets=None, **kwargs): + super().__init__(*args, **kwargs) + self.targets = targets or {} + if len(self.targets) > 1: + self.fields["site_key"] = forms.ChoiceField( + label="Website", + choices=[ + (key, site.domain) for key, site in self.targets.items() + ], + ) + self.order_fields(["site_key", "scope", "filename", "replace"]) + def clean_filename(self): filename = self.cleaned_data["filename"] if filename: @@ -102,6 +114,8 @@ class WebsiteRestoreForm(BackupRestoreForm): def clean(self): cleaned = super().clean() + if len(self.targets) == 1: + cleaned["site_key"] = next(iter(self.targets)) if cleaned.get("scope") == "file" and cleaned.get("filename") == "": self.add_error( "filename", "Enter the path of the file to restore." diff --git a/src/coulobre/hosting/account_backups.py b/src/coulobre/hosting/account_backups.py index c618a2b..26390be 100644 --- a/src/coulobre/hosting/account_backups.py +++ b/src/coulobre/hosting/account_backups.py @@ -8,6 +8,7 @@ from django.utils import timezone from coulobre.account_backup import AccountBackup from coulobre.web_node import WebSite +from .independent_websites import active_websites from .models import ( AccountBackupSchedule, HostingAccount, @@ -34,6 +35,7 @@ def account_backup_manifest(account, *, include_mailboxes=False): WebSite(account.pk, account.primary_domain), tuple(database.spec for database in account.databases.all()), mailboxes, + tuple(site.spec for site in active_websites(account)), ).manifest() diff --git a/src/coulobre/hosting/account_retirement.py b/src/coulobre/hosting/account_retirement.py index b1cb166..6a84776 100644 --- a/src/coulobre/hosting/account_retirement.py +++ b/src/coulobre/hosting/account_retirement.py @@ -13,6 +13,7 @@ from coulobre.node_retirement import RetirementRequest from coulobre.sftp_keys import public_key_fingerprint from coulobre.web_node import WebAlias, WebSite +from .independent_websites import active_websites from .models import ( AccountBackupExpiration, AccountRetirement, @@ -83,6 +84,10 @@ def account_inventory(account): .distinct() ) certificates.extend(tls_domains) + additional = list(active_websites(account)) + certificates.extend( + site.spec.domain for site in additional if site.https_enabled + ) sftp = getattr(account, "sftp", None) site_domains = WebActivation.objects.filter( plan__account=account, finished_at__isnull=False, problem="" @@ -101,7 +106,9 @@ def account_inventory(account): "site": website.manifest(), "aliases": [domain for domain, _ in aliases], "certificates": sorted(set(certificates)), - "website_domains": sorted(set(site_domains)), + "website_domains": sorted( + set(site_domains) | {site.spec.domain for site in additional} + ), "sftp_keys": sorted( public_key_fingerprint(key) for key in sftp.public_keys.splitlines() diff --git a/src/coulobre/hosting/admin.py b/src/coulobre/hosting/admin.py index 9763dc7..f6f3993 100644 --- a/src/coulobre/hosting/admin.py +++ b/src/coulobre/hosting/admin.py @@ -59,6 +59,7 @@ class HostingPlanAdmin(admin.ModelAdmin): list_display = ( "name", "description", + "website_limit", "database_limit", "mailbox_limit", "mailbox_quota_mib", diff --git a/src/coulobre/hosting/backup_restores.py b/src/coulobre/hosting/backup_restores.py index 84f1418..a213133 100644 --- a/src/coulobre/hosting/backup_restores.py +++ b/src/coulobre/hosting/backup_restores.py @@ -5,6 +5,7 @@ from django.db import transaction from coulobre.account_backup import AccountBackup from coulobre.web_node import WebSite +from .independent_websites import Operation, active_websites from .models import ComponentRestoreJob, HostingMailbox, WebsiteRestoreJob from .resource_requests import lock_hosting_account, require_active_services @@ -50,16 +51,40 @@ def available_restore_resources(backup, kind, current): return {key: spec for key, spec in current.items() if key in keys} +def current_website_restore_targets(account): + if account.retired_at is not None: + return {} + sites = [WebSite(account.pk, account.primary_domain)] + sites.extend( + website.spec + for website in active_websites(account).exclude( + operation=Operation.RETIRE, finished_at__isnull=True + ) + ) + return {site.node_key: site for site in sites} + + +def available_website_restore_targets(backup, current=None): + if current is None: + current = current_website_restore_targets(backup.account) + return { + key: site + for key, site in current.items() + if backup.can_restore_website(site) + } + + @transaction.atomic def queue_website_restore( - backup, *, restore_id, filename, replace, operator_username + backup, *, restore_id, filename, replace, operator_username, site_key=None ): account = lock_hosting_account(backup.account_id, customer_id=None) require_active_services(account) backup.refresh_from_db() - if not backup.can_restore_website( - WebSite(account.pk, account.primary_domain) - ): + backup.account = account + targets = available_website_restore_targets(backup) + site = targets.get(site_key or str(account.pk)) + if site is None: raise ValidationError( "Choose a completed backup of the current website." ) @@ -69,7 +94,13 @@ def queue_website_restore( backup, restore_id, operator_username, - {"filename": filename, "replace": replace}, + { + "filename": filename, + "replace": replace, + "site_manifest": site.manifest() + if site.site_id is not None + else None, + }, WebsiteRestoreJob.objects.filter( backup__account=account, finished_at__isnull=True ), diff --git a/src/coulobre/hosting/independent_website_views.py b/src/coulobre/hosting/independent_website_views.py new file mode 100644 index 0000000..c77d68c --- /dev/null +++ b/src/coulobre/hosting/independent_website_views.py @@ -0,0 +1,202 @@ +from django import forms +from django.conf import settings +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ValidationError +from django.db import IntegrityError +from django.http import Http404, JsonResponse +from django.shortcuts import get_object_or_404, redirect +from django.utils.functional import cached_property +from django.views import View +from django.views.generic import FormView +from django.views.generic.detail import SingleObjectMixin + +from coulobre.domain_names import canonical_domain + +from .access import OperatorOnlyMixin, TenantScopeMixin +from .independent_websites import ( + Operation, + account_websites, + allowed_versions, + create_website, + queue_website_operation, +) +from .models import HostingAccount, IndependentWebsite, WebsiteDomain + + +class WebsiteCreateForm(forms.Form): + domain = forms.CharField(max_length=253) + php_version = forms.CharField( + label="PHP series", + required=False, + max_length=5, + help_text="Leave blank to use the newest allowed stable series.", + ) + + def clean_domain(self): + try: + return canonical_domain(self.cleaned_data["domain"]) + except ValueError as error: + raise forms.ValidationError(str(error)) from error + + +class WebsiteOperationForm(forms.Form): + def __init__(self, *args, operation, domain, **kwargs): + super().__init__(*args, **kwargs) + self.operation = operation + self.domain = domain + if operation in (Operation.ACTIVATE, Operation.PHP): + self.fields["php_version"] = forms.CharField( + label="PHP series", + max_length=5, + required=operation == Operation.PHP, + ) + if operation == Operation.RETIRE: + self.fields["confirmation"] = forms.CharField( + label="Confirm the website domain", + max_length=253, + help_text=f"Enter {domain} to retire this website.", + ) + + def clean_confirmation(self): + value = self.cleaned_data["confirmation"] + if value != self.domain: + raise forms.ValidationError("Enter the website domain exactly.") + return value + + +class IndependentWebsiteEditor( + TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, FormView +): + queryset = HostingAccount.objects.filter( + retired_at__isnull=True + ).select_related("hosting_plan") + object = None + customer_relation = "customer" + permission_required = ( + "hosting.view_hostingaccount", + "hosting.change_hostingaccount", + ) + template_name = "hosting/independent_website_form.html" + + def dispatch(self, request, *args, **kwargs): + if not settings.LOCAL_WEB_ACTIVATION: + raise Http404 + return super().dispatch(request, *args, **kwargs) + + @cached_property + def account(self): + return self.get_object() + + def get_context_data(self, **kwargs): + return super().get_context_data( + account=self.account, + allowed_php_versions=allowed_versions(self.account), + **kwargs, + ) + + +class IndependentWebsiteCreate(IndependentWebsiteEditor): + form_class = WebsiteCreateForm + extra_context = {"title": "Add independent website", "add": True} + + def form_valid(self, form): + domain = form.cleaned_data["domain"] + try: + create_website( + self.account.pk, + domain, + form.cleaned_data["php_version"], + self.request.user, + ) + except HostingAccount.DoesNotExist as error: + raise Http404 from error + except ValidationError as error: + form.add_error(None, error) + return self.form_invalid(form) + except IntegrityError: + if not WebsiteDomain.objects.filter(domain=domain).exists(): + raise + form.add_error("domain", "This domain is unavailable.") + return self.form_invalid(form) + return redirect(self.account) + + +class IndependentWebsiteOperation(IndependentWebsiteEditor): + form_class = WebsiteOperationForm + + @cached_property + def operation(self): + try: + operation = Operation(self.kwargs["operation"]) + except ValueError: + raise Http404 from None + if operation == Operation.HTTPS and not settings.LOCAL_WEB_HTTPS: + raise Http404 + return operation + + @cached_property + def website(self): + return get_object_or_404( + account_websites(self.account), + pk=self.kwargs["site_pk"], + retired_at__isnull=True, + ) + + def get_initial(self): + return {"php_version": self.website.requested_php_version} + + def get_form_kwargs(self): + return super().get_form_kwargs() | { + "operation": self.operation, + "domain": self.website.reservation.domain, + } + + def get_context_data(self, **kwargs): + return super().get_context_data( + title=self.operation.label, + website=self.website, + retiring=self.operation == Operation.RETIRE, + **kwargs, + ) + + def form_valid(self, form): + try: + queue_website_operation( + self.account.pk, + self.website.pk, + self.operation, + form.cleaned_data.get("php_version", ""), + self.request.user, + ) + except (HostingAccount.DoesNotExist, IndependentWebsite.DoesNotExist): + raise Http404 from None + except ValidationError as error: + if self.operation == Operation.ACTIVATE: + form.add_error(None, " ".join(error.messages)) + else: + form.add_error(None, error) + return self.form_invalid(form) + return redirect(self.account) + + +class IndependentWebsiteManifest( + OperatorOnlyMixin, PermissionRequiredMixin, View +): + permission_required = "hosting.view_hostingaccount" + + def get(self, request, pk, site_pk): + website = get_object_or_404( + IndependentWebsite.objects.select_related("reservation"), + pk=site_pk, + reservation__account_id=pk, + ) + return JsonResponse( + website.spec.manifest(), + headers={ + "Cache-Control": "private, no-store", + "Content-Disposition": ( + "attachment; " + f'filename="coulobre-website-{website.pk}.json"' + ), + }, + ) diff --git a/src/coulobre/hosting/independent_websites.py b/src/coulobre/hosting/independent_websites.py new file mode 100644 index 0000000..8df1cd9 --- /dev/null +++ b/src/coulobre/hosting/independent_websites.py @@ -0,0 +1,195 @@ +from django.conf import settings +from django.core.exceptions import PermissionDenied, ValidationError +from django.db import transaction +from django.utils import timezone + +from coulobre.node_retirement import RetirementRequest +from coulobre.php_pool_settings import PhpPoolSettings +from coulobre.php_runtime import validate_php_version +from coulobre.service_access import ServiceAccessRequest + +from .access import is_tenant, manages_account +from .models import IndependentWebsite, WebsiteDomain, WebsiteRestoreJob +from .node_client import ( + activate_local_site, + apply_on_local_node, + enable_local_https, + set_local_site_storage_limit, + update_local_php_version, +) +from .resource_requests import lock_hosting_account, require_active_services + +Operation = IndependentWebsite.Operation + + +def account_websites(account): + return ( + IndependentWebsite.objects.filter(reservation__account=account) + .select_related("reservation") + .order_by("reservation__domain") + ) + + +def active_websites(account): + return account_websites(account).filter( + activated=True, retired_at__isnull=True + ) + + +def website_limit(account): + plan = account.hosting_plan + return plan.website_limit if plan is not None else 1 + + +def allowed_versions(account): + plan = account.hosting_plan + return plan.allowed_php_versions() if plan is not None else () + + +def website_actions(website): + if website.finished_at is None or website.retired_at is not None: + return () + if not website.activated: + return (Operation.ACTIVATE, Operation.RETIRE) + if website.suspended: + return (Operation.RESUME, Operation.RETIRE) + actions = (Operation.PHP, Operation.SUSPEND) + if settings.LOCAL_WEB_HTTPS and not website.https_enabled: + actions += (Operation.HTTPS,) + return actions + + +def check_actor(account, actor): + if is_tenant(actor) and not manages_account(actor, account): + raise PermissionDenied + + +def check_version(account, version): + try: + validate_php_version(version) + except ValueError as error: + raise ValidationError({"php_version": str(error)}) from error + allowed = allowed_versions(account) + if allowed and version not in allowed: + raise ValidationError( + {"php_version": "This PHP series is outside the hosting plan."} + ) + + +@transaction.atomic +def create_website(account_id, domain, version, actor): + account = lock_hosting_account(account_id, customer_id=None) + check_actor(account, actor) + require_active_services(account) + if account_websites(account).filter( + retired_at__isnull=True + ).count() + 1 >= website_limit(account): + raise ValidationError( + "This hosting account has reached its website limit." + ) + if version: + check_version(account, version) + if WebsiteDomain.objects.filter(domain=domain).exists(): + raise ValidationError({"domain": "This domain is unavailable."}) + reservation = WebsiteDomain.objects.create(account=account, domain=domain) + return IndependentWebsite.objects.create( + reservation=reservation, requested_php_version=version + ) + + +@transaction.atomic +def queue_website_operation(account_id, site_id, operation, version, actor): + account = lock_hosting_account(account_id, customer_id=None) + check_actor(account, actor) + require_active_services(account) + website = ( + account_websites(account) + .select_for_update() + .get(pk=site_id, retired_at__isnull=True) + ) + if operation not in Operation.values: + raise ValidationError("Choose a website operation.") + if website.finished_at is None: + raise ValidationError("Wait for the current website operation.") + if operation not in website_actions(website): + raise ValidationError( + "This operation is unavailable for this website." + ) + if operation == Operation.PHP or version: + check_version(account, version) + if operation == Operation.RETIRE and ( + account.backup_jobs.filter(finished_at__isnull=True).exists() + or WebsiteRestoreJob.objects.filter( + backup__account=account, finished_at__isnull=True + ).exists() + ): + raise ValidationError("Wait for the backup or restore to finish.") + IndependentWebsite.objects.requeue( + IndependentWebsite.objects.filter(pk=website.pk), + operation=operation, + requested_php_version=( + version + if operation in (Operation.ACTIVATE, Operation.PHP) + else website.requested_php_version + ), + ) + return website + + +def apply_website_operation(website): + site = website.spec + operation = website.operation + account = website.reservation.account + try: + require_active_services(account) + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + if operation in (Operation.ACTIVATE, Operation.PHP): + requested = website.requested_php_version + if requested: + try: + check_version(account, requested) + except ValidationError as error: + raise ValueError(" ".join(error.messages)) from None + if operation == Operation.ACTIVATE: + plan = account.hosting_plan + _, version = activate_local_site( + site, + plan.get_php_settings() if plan else PhpPoolSettings(), + (requested,) if requested else allowed_versions(account), + ) + limit = plan.website_storage_limit_mib if plan else None + if limit is not None: + set_local_site_storage_limit(site, limit) + return { + "activated": True, + "php_version": version, + "storage_limit_mib": limit, + } + if operation == Operation.PHP: + return {"php_version": update_local_php_version(site, requested)} + if operation == Operation.HTTPS: + if not settings.LOCAL_WEB_HTTPS: + raise ValueError("Enable the website HTTPS worker first.") + enable_local_https(site) + return {"https_enabled": True} + if operation in (Operation.SUSPEND, Operation.RESUME): + suspended = operation == Operation.SUSPEND + apply_on_local_node( + ServiceAccessRequest(site, suspended), + "/run/coulobre-web-apply.sock", + "web node", + "website access", + ) + return {"suspended": suspended} + if operation == Operation.RETIRE: + request = RetirementRequest(site, str(website.retirement_id)) + apply_on_local_node( + request, + "/run/coulobre-web-apply.sock", + "web node", + "website retirement", + identity=request.identity(), + ) + return {"retired_at": timezone.now()} + raise ValueError("Unknown website operation.") diff --git a/src/coulobre/hosting/migrations/0047_independent_websites.py b/src/coulobre/hosting/migrations/0047_independent_websites.py new file mode 100644 index 0000000..dfd24f0 --- /dev/null +++ b/src/coulobre/hosting/migrations/0047_independent_websites.py @@ -0,0 +1,106 @@ +# Generated by Django 5.2.19 on 2026-11-22 10:56 + +import uuid + +import django.core.validators +import django.db.models.deletion +import django.utils.timezone +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0046_reseller_onboarding"), + ] + + operations = [ + migrations.AddField( + model_name="hostingplan", + name="website_limit", + field=models.PositiveSmallIntegerField( + default=1, + help_text=( + "Maximum independent websites, including the primary site." + ), + validators=[django.core.validators.MinValueValidator(1)], + ), + ), + migrations.AddField( + model_name="websiterestorejob", + name="site_manifest", + field=models.JSONField(blank=True, null=True), + ), + migrations.CreateModel( + name="IndependentWebsite", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "requested_at", + models.DateTimeField(default=django.utils.timezone.now), + ), + ( + "last_dispatched_at", + models.DateTimeField(blank=True, null=True), + ), + ("started_at", models.DateTimeField(blank=True, null=True)), + ("finished_at", models.DateTimeField(blank=True, null=True)), + ("problem", models.TextField(blank=True)), + ( + "operation", + models.CharField( + choices=[ + ("activate", "Provision website"), + ("php", "Change PHP series"), + ("https", "Enable HTTPS"), + ("suspend", "Suspend website"), + ("resume", "Resume website"), + ("retire", "Retire website"), + ], + default="activate", + max_length=8, + ), + ), + ("activated", models.BooleanField(default=False)), + ("https_enabled", models.BooleanField(default=False)), + ("suspended", models.BooleanField(default=False)), + ("retired_at", models.DateTimeField(blank=True, null=True)), + ( + "requested_php_version", + models.CharField(blank=True, max_length=5), + ), + ("php_version", models.CharField(blank=True, max_length=5)), + ( + "storage_limit_mib", + models.PositiveIntegerField(blank=True, null=True), + ), + ( + "retirement_id", + models.UUIDField(default=uuid.uuid4, editable=False), + ), + ( + "reservation", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="website", + to="hosting.websitedomain", + ), + ), + ], + options={ + "indexes": [ + models.Index( + fields=["operation", "finished_at", "requested_at"], + name="hosting_ind_operati_bc432b_idx", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 02214f4..8e0dd0b 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -39,7 +39,7 @@ from coulobre.php_pool_settings import ( PhpPoolSettingsError, ) from coulobre.php_runtime import validate_php_versions -from coulobre.web_node import MAX_STORAGE_LIMIT_MIB +from coulobre.web_node import MAX_STORAGE_LIMIT_MIB, WebSite from .fields import DomainNameField @@ -262,6 +262,11 @@ def php_plan_field(option, label): class HostingPlan(models.Model): name = models.CharField(max_length=120, unique=True) description = models.CharField(max_length=240, blank=True) + website_limit = models.PositiveSmallIntegerField( + default=1, + validators=[MinValueValidator(1)], + help_text="Maximum independent websites, including the primary site.", + ) database_limit = models.PositiveIntegerField( blank=True, null=True, @@ -893,6 +898,45 @@ class WebsiteAlias(ProvisioningJob): ] +class IndependentWebsite(ProvisioningJob): + class Operation(models.TextChoices): + ACTIVATE = "activate", "Provision website" + PHP = "php", "Change PHP series" + HTTPS = "https", "Enable HTTPS" + SUSPEND = "suspend", "Suspend website" + RESUME = "resume", "Resume website" + RETIRE = "retire", "Retire website" + + reservation = models.OneToOneField( + WebsiteDomain, on_delete=models.CASCADE, related_name="website" + ) + operation = models.CharField( + max_length=8, choices=Operation, default=Operation.ACTIVATE + ) + activated = models.BooleanField(default=False) + https_enabled = models.BooleanField(default=False) + suspended = models.BooleanField(default=False) + retired_at = models.DateTimeField(null=True, blank=True) + requested_php_version = models.CharField(max_length=5, blank=True) + php_version = models.CharField(max_length=5, blank=True) + storage_limit_mib = models.PositiveIntegerField(null=True, blank=True) + retirement_id = models.UUIDField(default=uuid.uuid4, editable=False) + + class Meta: + indexes = [ + models.Index(fields=("operation", "finished_at", "requested_at")) + ] + + def __str__(self): + return self.reservation.domain + + @property + def spec(self): + return WebSite( + self.reservation.account_id, self.reservation.domain, self.pk + ) + + class SiteSFTP(ProvisioningJob): account = models.OneToOneField( HostingAccount, on_delete=models.CASCADE, related_name="sftp" @@ -947,9 +991,9 @@ class AccountBackupJob(ProvisioningJob): return expiration is None or expiration.finished_at is not None def can_restore_website(self, site): - return ( - self.archive_is_restorable - and self.manifest.get("website") == site.manifest() + return self.archive_is_restorable and ( + self.manifest.get("website") == site.manifest() + or site.manifest() in self.manifest.get("additional_websites", []) ) @@ -973,6 +1017,7 @@ class WebsiteRestoreJob(ProvisioningJob): related_name="website_restores", ) restore_id = models.UUIDField(unique=True, editable=False) + site_manifest = models.JSONField(null=True, blank=True) filename = models.CharField(max_length=MAX_RESTORE_PATH_BYTES, blank=True) replace = models.BooleanField(default=False) operator_username = models.CharField(max_length=150) diff --git a/src/coulobre/hosting/service_changes.py b/src/coulobre/hosting/service_changes.py index df98172..45ff69a 100644 --- a/src/coulobre/hosting/service_changes.py +++ b/src/coulobre/hosting/service_changes.py @@ -8,6 +8,7 @@ from coulobre.mail_node import MailboxSpec from coulobre.service_access import ServiceAccessRequest from coulobre.web_node import WebSite +from .independent_websites import account_websites, active_websites from .models import ( AccountServiceJob, ComponentRestoreJob, @@ -62,6 +63,11 @@ def current_service_jobs(account): "Resolve pending or failed website, database, and mailbox " "provisioning before suspending services." ) + websites = account_websites(account).filter(retired_at__isnull=True) + if websites.filter(Q(finished_at__isnull=True) | ~Q(problem="")).exists(): + raise ValidationError( + "Resolve pending or failed website operations first." + ) component_restores = ComponentRestoreJob.objects.filter( backup__account=account ) @@ -81,6 +87,9 @@ def current_service_jobs(account): yield Kind.WEB, domain, site.manifest() if settings.LOCAL_WEB_SFTP or hasattr(account, "sftp"): yield Kind.SFTP, domain, site.manifest() + for website in active_websites(account): + site = website.spec + yield Kind.WEB, site.domain, site.manifest() completed_restores = component_restores.filter(problem="") restored_databases = completed_restores.filter( kind=ComponentRestoreJob.Kind.DATABASE @@ -176,9 +185,16 @@ def apply_service_change(job): raise ValueError( f"The provisioning worker for {job.target} is disabled." ) - request = ServiceAccessRequest( - resource.from_manifest(job.manifest), job.change.suspended - ) + spec = resource.from_manifest(job.manifest) + suspended = job.change.suspended + if job.kind == Kind.WEB and spec.site_id is not None and not suspended: + website = ( + active_websites(job.change.account).filter(pk=spec.site_id).first() + ) + if website is None or website.spec != spec: + raise ValueError("The additional website has changed.") + suspended = website.suspended + request = ServiceAccessRequest(spec, suspended) apply_on_local_node( request, socket, job.get_kind_display(), "service access" ) diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index e0b115e..cad6e2f 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -29,10 +29,12 @@ 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 ( @@ -45,6 +47,7 @@ from .models import ( DatabaseProvisioning, DnsPublication, HostingMailDomain, + IndependentWebsite, MailboxProvisioning, MailRoutingPublication, MailVacationPublication, @@ -140,6 +143,12 @@ def render_web_plan(plan_id): @shared_task def dispatch_web_activations(): if settings.LOCAL_WEB_ACTIVATION: + 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 ) @@ -180,6 +189,12 @@ def dispatch_site_storage_limits(): @shared_task def dispatch_web_https(): if settings.LOCAL_WEB_HTTPS: + 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( @@ -739,6 +754,11 @@ 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.") + 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: @@ -823,8 +843,15 @@ def restore_website(job_id): def apply_website_restore(job): account = job.backup.account - site = WebSite(account.pk, account.primary_domain) - if not job.backup.can_restore_website(site): + 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( @@ -922,3 +949,16 @@ def expire_sign_in_windows(): @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.", + ) diff --git a/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html b/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html index 583c0a6..767aa0a 100644 --- a/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html +++ b/src/coulobre/hosting/templates/hosting/account_backup_archive_table.html @@ -15,7 +15,9 @@ Manual {% endif %} - {% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %} + + {% if job.manifest.additional_websites %}Websites{% else %}Website{% endif %}{% if job.includes_mailboxes %}, databases, and mail{% else %} and databases{% endif %} + {% if job.expired_at %} Expired diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index a93e5fb..be0ac05 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -60,6 +60,7 @@