Host independent websites within a hosting account #102
No files matched your search
@@ -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
|
||||
|
||||
+6
-2
@@ -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-<suffix>.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/<domain>/<local-part>.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<site_id>.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<site_id>.json` and
|
||||
`websites/s<site_id>.tar.gz` pair with the same command.
|
||||
Use each `database-<suffix>.json` and `database-<suffix>.sql.gz` pair with
|
||||
`restore-database`. For mail, use the original manifest and archive recovered
|
||||
as `mailboxes/<domain>/<local-part>.json` and
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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."
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -59,6 +59,7 @@ class HostingPlanAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"name",
|
||||
"description",
|
||||
"website_limit",
|
||||
"database_limit",
|
||||
"mailbox_limit",
|
||||
"mailbox_quota_mib",
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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"'
|
||||
),
|
||||
},
|
||||
)
|
||||
@@ -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.")
|
||||
@@ -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",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -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.",
|
||||
)
|
||||
@@ -15,7 +15,9 @@
|
||||
Manual
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{% if job.includes_mailboxes %}Website, databases, and mail{% else %}Website and databases{% endif %}</td>
|
||||
<td>
|
||||
{% if job.manifest.additional_websites %}Websites{% else %}Website{% endif %}{% if job.includes_mailboxes %}, databases, and mail{% else %} and databases{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
{% if job.expired_at %}
|
||||
Expired
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
<nav class="account-navigation" aria-label="On this account">
|
||||
{% if can_change_hosting_services or service_change %}<a href="#service-access-heading">Services</a>{% endif %}
|
||||
{% if show_website %}<a href="#account-website">Website</a>{% endif %}
|
||||
{% if independent_websites or add_independent_website %}<a href="#independent-websites">Independent websites</a>{% endif %}
|
||||
{% if is_tenant or perms.hosting.view_hostingdatabase %}<a href="#databases-heading">Databases</a>{% endif %}
|
||||
{% if is_tenant or perms.hosting.view_hostingdnszone %}<a href="#dns-zones-heading">DNS</a>{% endif %}
|
||||
{% if is_tenant or perms.hosting.view_hostingmailbox %}<a href="#mailboxes-heading">Mailboxes</a>{% endif %}
|
||||
@@ -96,6 +97,9 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if independent_websites or add_independent_website %}
|
||||
{% include "hosting/independent_websites.html" %}
|
||||
{% endif %}
|
||||
{% if is_tenant or perms.hosting.view_hostingdatabase %}
|
||||
<section class="surface" aria-labelledby="databases-heading">
|
||||
<header class="section-heading">
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}{{ title }} · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}#independent-websites">← {{ account.name }}</a>
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>{{ title }}</h1>
|
||||
{% if website %}<p class="heading-meta domain">{{ website }}</p>{% endif %}
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
{% if add %}<p>This website has its own document root and PHP runtime. Point the domain at this web server before enabling HTTPS.</p>{% endif %}
|
||||
{% if retiring %}<p>Retirement takes this website offline and archives its files on the web server. Its domain stays reserved.</p>{% endif %}
|
||||
{% if allowed_php_versions %}<p>Allowed PHP series {{ allowed_php_versions|join:", " }}</p>{% endif %}
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">{{ title }}</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}#independent-websites">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,44 @@
|
||||
<section class="surface" aria-labelledby="independent-websites">
|
||||
<header class="section-heading">
|
||||
<h2 id="independent-websites" tabindex="-1">Independent websites</h2>
|
||||
{% if add_independent_website %}<a class="button primary" href="{% url 'panel:independent_website_create' account.pk %}">Add website</a>{% endif %}
|
||||
</header>
|
||||
{% if independent_websites %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr><th scope="col">Domain</th><th scope="col">Status</th><th scope="col">PHP</th><th scope="col">Storage limit</th><th scope="col">Actions</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for website, actions in independent_websites %}
|
||||
<tr>
|
||||
<th scope="row" class="domain">{{ website }}</th>
|
||||
<td>
|
||||
{% if website.retired_at %}<span class="status suspended">Retired</span>
|
||||
{% elif website.suspended or account.services_suspended %}<span class="status suspended">Suspended</span>
|
||||
{% elif website.activated %}<span class="status ready">Active</span>
|
||||
{% endif %}
|
||||
{% if website.https_enabled %}<span class="status ready">HTTPS</span>{% endif %}
|
||||
{% if website.state == "failed" %}<p role="status">{{ website.get_operation_display }} failed{% if is_operator %}. {{ website.problem }}{% endif %}</p>
|
||||
{% elif website.state == "queued" or website.state == "running" %}<p role="status">{{ website.get_operation_display }} · {{ website.state }}</p>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>{{ website.php_version|default:"—" }}</td>
|
||||
<td>{% if website.storage_limit_mib %}{{ website.storage_limit_mib }} MiB{% elif website.activated %}Unlimited{% else %}—{% endif %}</td>
|
||||
<td><div class="table-actions">
|
||||
{% for action in actions %}
|
||||
<a class="record-link" href="{% url 'panel:independent_website_operation' account.pk website.pk action.value %}">{{ action.label }}</a>
|
||||
{% endfor %}
|
||||
{% if is_operator and perms.hosting.view_hostingaccount %}
|
||||
<a class="record-link" href="{% url 'panel:independent_website_manifest' account.pk website.pk %}">Download manifest</a>
|
||||
{% endif %}
|
||||
</div></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No independent websites have been added.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
@@ -5,7 +5,7 @@
|
||||
<header class="page-heading">
|
||||
<div>
|
||||
<h1>Restore website</h1>
|
||||
<p class="heading-meta">{{ account.primary_domain }} · Backup requested {{ backup.requested_at|date:"j M Y, H:i" }} UTC</p>
|
||||
<p class="heading-meta">{% if restore_site %}{{ restore_site.domain }} · {% endif %}Backup requested {{ backup.requested_at|date:"j M Y, H:i" }} UTC</p>
|
||||
</div>
|
||||
</header>
|
||||
<section class="surface editor-surface">
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
from unittest.mock import patch
|
||||
from uuid import uuid4
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import SimpleTestCase, TestCase, override_settings
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
from coulobre.account_backup import AccountBackup
|
||||
from coulobre.account_restore_request import component_filename
|
||||
from coulobre.php_pool_settings import PhpPoolSettings
|
||||
from coulobre.web_node import WebSite
|
||||
from coulobre.web_node_apply import SitePaths
|
||||
from coulobre.web_node_tls import certbot_lineage
|
||||
|
||||
from .account_backups import account_backup_manifest
|
||||
from .models import (
|
||||
AccountBackupJob,
|
||||
Customer,
|
||||
HostingAccount,
|
||||
HostingPlan,
|
||||
IndependentWebsite,
|
||||
WebsiteDomain,
|
||||
WebsiteRestoreJob,
|
||||
)
|
||||
from .service_changes import apply_service_change, request_service_change
|
||||
from .tasks import apply_website_restore, provision_independent_website
|
||||
|
||||
Operation = IndependentWebsite.Operation
|
||||
|
||||
|
||||
class WebsiteIdentityTests(SimpleTestCase):
|
||||
def test_independent_site_keeps_account_id_and_separate_node_paths(self):
|
||||
primary = WebSite(17, "example.test")
|
||||
child = WebSite(17, "shop.example.test", 17)
|
||||
self.assertEqual(primary.manifest()["version"], 1)
|
||||
self.assertEqual(child.manifest()["version"], 2)
|
||||
self.assertEqual(WebSite.from_manifest(child.manifest()), child)
|
||||
self.assertEqual(primary.service_user, "coulobre-17")
|
||||
self.assertEqual(child.service_user, "coulobre-s17")
|
||||
self.assertEqual(SitePaths.for_site(child).account.name, "s17")
|
||||
self.assertEqual(certbot_lineage(child).name, "coulobre-s17")
|
||||
self.assertIn(
|
||||
"/srv/coulobre/web/s17/public",
|
||||
child.render("apache"),
|
||||
)
|
||||
self.assertNotEqual(
|
||||
SitePaths.for_site(child), SitePaths.for_site(primary)
|
||||
)
|
||||
|
||||
def test_multisite_bundle_identifies_children_and_rejects_foreign_sites(
|
||||
self,
|
||||
):
|
||||
primary = WebSite(17, "example.test")
|
||||
child = WebSite(17, "shop.example.test", 19)
|
||||
spec = AccountBackup(primary, (), additional_websites=(child,))
|
||||
self.assertEqual(spec.manifest()["version"], 3)
|
||||
self.assertEqual(AccountBackup.from_manifest(spec.manifest()), spec)
|
||||
self.assertEqual(
|
||||
component_filename(spec, child), "websites/s19.tar.gz"
|
||||
)
|
||||
self.assertIsNone(
|
||||
component_filename(spec, WebSite(17, child.domain, 20))
|
||||
)
|
||||
with self.assertRaisesMessage(
|
||||
ValueError, "belong to the backup account"
|
||||
):
|
||||
AccountBackup(
|
||||
primary,
|
||||
(),
|
||||
additional_websites=(WebSite(42, child.domain, 19),),
|
||||
)
|
||||
|
||||
|
||||
@override_settings(
|
||||
LOCAL_WEB_ACTIVATION=True,
|
||||
LOCAL_WEB_HTTPS=True,
|
||||
LOCAL_ACCOUNT_BACKUPS=True,
|
||||
LOCAL_WEBSITE_RESTORE=True,
|
||||
)
|
||||
class IndependentWebsiteTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.owner = users.create_user("owner")
|
||||
cls.outsider = users.create_user("outsider")
|
||||
Customer.objects.create(user=cls.outsider)
|
||||
cls.plan = HostingPlan.objects.create(
|
||||
name="Two websites",
|
||||
website_limit=2,
|
||||
php_versions="8.4,8.5",
|
||||
website_storage_limit_mib=200,
|
||||
)
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Example",
|
||||
primary_domain="example.test",
|
||||
customer=Customer.objects.create(user=cls.owner),
|
||||
hosting_plan=cls.plan,
|
||||
)
|
||||
cls.other = HostingAccount.objects.create(
|
||||
name="Elsewhere",
|
||||
primary_domain="foreign.test",
|
||||
customer=cls.outsider.hosting_customer,
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.client.force_login(self.owner)
|
||||
self.add = reverse(
|
||||
"panel:independent_website_create", args=[self.account.pk]
|
||||
)
|
||||
|
||||
def create_website(self):
|
||||
response = self.client.post(
|
||||
self.add, {"domain": "SHOP.Example.Test.", "php_version": "8.4"}
|
||||
)
|
||||
self.assertRedirects(response, self.account.get_absolute_url())
|
||||
return IndependentWebsite.objects.get()
|
||||
|
||||
def active_website(self):
|
||||
website = self.create_website()
|
||||
IndependentWebsite.objects.filter(pk=website.pk).update(
|
||||
activated=True, php_version="8.4", finished_at=timezone.now()
|
||||
)
|
||||
website.refresh_from_db()
|
||||
return website
|
||||
|
||||
def operation(self, website, action, data=None):
|
||||
return self.client.post(
|
||||
reverse(
|
||||
"panel:independent_website_operation",
|
||||
args=[self.account.pk, website.pk, action],
|
||||
),
|
||||
data or {},
|
||||
)
|
||||
|
||||
def test_scoped_creation_and_quota_inherit_plan(self):
|
||||
response = self.client.post(self.add, {"domain": "foreign.test"})
|
||||
self.assertContains(response, "This domain is unavailable.")
|
||||
response = self.client.post(
|
||||
self.add, {"domain": "shop.example.test", "php_version": "8.3"}
|
||||
)
|
||||
self.assertContains(response, "outside the hosting plan")
|
||||
website = self.create_website()
|
||||
self.assertContains(
|
||||
self.client.get(self.account.get_absolute_url()),
|
||||
"shop.example.test",
|
||||
)
|
||||
self.assertContains(
|
||||
self.client.post(self.add, {"domain": "overflow.example.test"}),
|
||||
"has reached its website limit",
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"coulobre.hosting.independent_websites.activate_local_site",
|
||||
return_value=(PhpPoolSettings(), "8.4"),
|
||||
) as activate,
|
||||
patch(
|
||||
"coulobre.hosting.independent_websites.set_local_site_storage_limit"
|
||||
) as quota,
|
||||
):
|
||||
provision_independent_website.run(website.pk)
|
||||
activate.assert_called_once_with(
|
||||
website.spec, self.plan.get_php_settings(), ("8.4",)
|
||||
)
|
||||
quota.assert_called_once_with(website.spec, 200)
|
||||
website.refresh_from_db()
|
||||
self.assertEqual(website.storage_limit_mib, 200)
|
||||
self.assertEqual(website.php_version, "8.4")
|
||||
self.assertContains(
|
||||
self.client.get(self.account.get_absolute_url()),
|
||||
"Change PHP series",
|
||||
)
|
||||
self.assertRedirects(
|
||||
self.operation(website, Operation.PHP, {"php_version": "8.5"}),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
with patch(
|
||||
"coulobre.hosting.independent_websites.update_local_php_version",
|
||||
return_value="8.5",
|
||||
) as switch:
|
||||
provision_independent_website.run(website.pk)
|
||||
switch.assert_called_once_with(website.spec, "8.5")
|
||||
website.refresh_from_db()
|
||||
self.assertEqual(website.php_version, "8.5")
|
||||
self.client.force_login(self.outsider)
|
||||
self.assertEqual(self.client.get(self.add).status_code, 404)
|
||||
self.assertEqual(
|
||||
self.operation(website, Operation.SUSPEND).status_code, 404
|
||||
)
|
||||
|
||||
def test_tls_and_retirement_leave_primary_reservation_intact(self):
|
||||
website = self.active_website()
|
||||
self.assertRedirects(
|
||||
self.operation(website, Operation.HTTPS),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
with patch(
|
||||
"coulobre.hosting.independent_websites.enable_local_https"
|
||||
) as tls:
|
||||
provision_independent_website.run(website.pk)
|
||||
tls.assert_called_once_with(website.spec)
|
||||
self.assertRedirects(
|
||||
self.operation(website, Operation.SUSPEND),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
with patch(
|
||||
"coulobre.hosting.independent_websites.apply_on_local_node"
|
||||
) as node:
|
||||
provision_independent_website.run(website.pk)
|
||||
request = node.call_args.args[0]
|
||||
self.assertEqual(request.resource, website.spec)
|
||||
self.assertTrue(request.suspended)
|
||||
self.assertContains(
|
||||
self.operation(
|
||||
website, Operation.RETIRE, {"confirmation": "wrong"}
|
||||
),
|
||||
"Enter the website domain exactly.",
|
||||
)
|
||||
self.assertRedirects(
|
||||
self.operation(
|
||||
website, Operation.RETIRE, {"confirmation": str(website)}
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
with patch(
|
||||
"coulobre.hosting.independent_websites.apply_on_local_node"
|
||||
) as node:
|
||||
provision_independent_website.run(website.pk)
|
||||
self.assertEqual(node.call_args.args[0].resource, website.spec)
|
||||
website.refresh_from_db()
|
||||
self.assertTrue(website.https_enabled)
|
||||
self.assertIsNotNone(website.retired_at)
|
||||
self.assertTrue(
|
||||
WebsiteDomain.objects.filter(
|
||||
account=self.account, is_primary=True
|
||||
).exists()
|
||||
)
|
||||
self.assertContains(
|
||||
self.client.post(self.add, {"domain": "shop.example.test"}),
|
||||
"This domain is unavailable.",
|
||||
)
|
||||
|
||||
def test_account_resume_preserves_an_independently_suspended_site(self):
|
||||
website = self.active_website()
|
||||
IndependentWebsite.objects.filter(pk=website.pk).update(suspended=True)
|
||||
request_service_change(self.account.pk, "suspend", "operator")
|
||||
self.account.service_changes.first().jobs.update(
|
||||
finished_at=timezone.now(), applied_suspended=True
|
||||
)
|
||||
request_service_change(self.account.pk, "resume", "operator")
|
||||
job = self.account.service_changes.first().jobs.get()
|
||||
with patch(
|
||||
"coulobre.hosting.service_changes.apply_on_local_node"
|
||||
) as node:
|
||||
apply_service_change(job)
|
||||
self.assertEqual(node.call_args.args[0].resource, website.spec)
|
||||
self.assertTrue(node.call_args.args[0].suspended)
|
||||
|
||||
def test_restore_selects_exact_website_from_account_archive(self):
|
||||
website = self.active_website()
|
||||
backup = AccountBackupJob.objects.create(
|
||||
account=self.account,
|
||||
manifest=account_backup_manifest(self.account),
|
||||
finished_at=timezone.now(),
|
||||
)
|
||||
self.assertEqual(
|
||||
backup.manifest["additional_websites"], [website.spec.manifest()]
|
||||
)
|
||||
self.client.force_login(self.operator)
|
||||
location = reverse(
|
||||
"panel:website_restore", args=[self.account.pk, backup.pk]
|
||||
)
|
||||
page = self.client.get(location)
|
||||
self.assertContains(page, "shop.example.test")
|
||||
data = {
|
||||
"scope": "file",
|
||||
"filename": "index.php",
|
||||
"restore_id": uuid4(),
|
||||
}
|
||||
response = self.client.post(location, data | {"site_key": "s999"})
|
||||
self.assertIn("site_key", response.context["form"].errors)
|
||||
self.assertRedirects(
|
||||
self.client.post(
|
||||
location, data | {"site_key": website.spec.node_key}
|
||||
),
|
||||
self.account.get_absolute_url(),
|
||||
)
|
||||
job = WebsiteRestoreJob.objects.get()
|
||||
self.assertEqual(job.site_manifest, website.spec.manifest())
|
||||
with patch("coulobre.hosting.tasks.restore_local_website") as restore:
|
||||
apply_website_restore(job)
|
||||
self.assertEqual(restore.call_args.args[0].site, website.spec)
|
||||
@@ -5,6 +5,11 @@ from . import views
|
||||
from .backup_restores import RestoreKind
|
||||
from .credential_views import DatabaseCredentialView, MailboxCredentialView
|
||||
from .health_views import ServiceHealthView
|
||||
from .independent_website_views import (
|
||||
IndependentWebsiteCreate,
|
||||
IndependentWebsiteManifest,
|
||||
IndependentWebsiteOperation,
|
||||
)
|
||||
from .mail_dns_views import MailDnsCheckView, RequestMailDnsSetup
|
||||
from .mail_policy_views import MailRoutingEditor, MailVacationEditor
|
||||
from .password_reset import (
|
||||
@@ -77,6 +82,21 @@ urlpatterns = [
|
||||
name="account_retirement",
|
||||
),
|
||||
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
|
||||
path(
|
||||
"accounts/<int:pk>/websites/new/",
|
||||
IndependentWebsiteCreate.as_view(),
|
||||
name="independent_website_create",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/websites/<int:site_pk>/manifest/",
|
||||
IndependentWebsiteManifest.as_view(),
|
||||
name="independent_website_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/websites/<int:site_pk>/<str:operation>/",
|
||||
IndependentWebsiteOperation.as_view(),
|
||||
name="independent_website_operation",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/customers/new/",
|
||||
ResellerCustomerCreate.as_view(),
|
||||
|
||||
@@ -33,7 +33,6 @@ from coulobre.dns_node import MAX_SOA_SERIAL
|
||||
from coulobre.mail_node import INVALID_LOCAL_PART
|
||||
from coulobre.php_runtime import available_php_versions
|
||||
from coulobre.sftp_keys import public_key_fingerprint
|
||||
from coulobre.web_node import WebSite
|
||||
|
||||
from .access import (
|
||||
OperatorOnlyMixin,
|
||||
@@ -60,7 +59,9 @@ from .account_backups import (
|
||||
from .backup_restores import (
|
||||
RestoreKind,
|
||||
available_restore_resources,
|
||||
available_website_restore_targets,
|
||||
current_restore_resources,
|
||||
current_website_restore_targets,
|
||||
enabled_component_restores,
|
||||
queue_component_restore,
|
||||
queue_website_restore,
|
||||
@@ -79,6 +80,11 @@ from .impersonation import (
|
||||
start_impersonation,
|
||||
support_write_session,
|
||||
)
|
||||
from .independent_websites import (
|
||||
account_websites,
|
||||
website_actions,
|
||||
website_limit,
|
||||
)
|
||||
from .mail_policy_views import mail_policy_enabled
|
||||
from .models import (
|
||||
AccountBackupJob,
|
||||
@@ -378,6 +384,21 @@ class AccountDetail(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
.filter(user__is_active=True)
|
||||
.exists()
|
||||
)
|
||||
if settings.LOCAL_WEB_ACTIVATION:
|
||||
websites = list(account_websites(self.object))
|
||||
can_manage = (
|
||||
not self.object.services_suspended
|
||||
and (tenant or user.has_perm(CHANGE_ACCOUNTS))
|
||||
and getattr(self.request, "impersonation", None) is None
|
||||
)
|
||||
context["independent_websites"] = [
|
||||
(website, website_actions(website) if can_manage else ())
|
||||
for website in websites
|
||||
]
|
||||
context["add_independent_website"] = can_manage and (
|
||||
sum(website.retired_at is None for website in websites) + 1
|
||||
< website_limit(self.object)
|
||||
)
|
||||
context["can_retire_account"] = not tenant and user.has_perms(
|
||||
RETIRE_ACCOUNTS
|
||||
)
|
||||
@@ -1114,11 +1135,11 @@ def backup_restore_context(account, user, backups, can_view_mailboxes):
|
||||
]
|
||||
)
|
||||
if settings.LOCAL_WEBSITE_RESTORE:
|
||||
site = WebSite(account.pk, account.primary_domain)
|
||||
current = current_website_restore_targets(account)
|
||||
context["website_restore_sources"] = {
|
||||
backup.pk
|
||||
for backup in backups
|
||||
if backup.can_restore_website(site)
|
||||
if available_website_restore_targets(backup, current)
|
||||
}
|
||||
if kinds:
|
||||
history.extend(
|
||||
@@ -1195,11 +1216,24 @@ class RequestWebsiteRestore(BackupRestoreView):
|
||||
|
||||
def get_backup(self):
|
||||
backup = super().get_backup()
|
||||
site = WebSite(backup.account_id, backup.account.primary_domain)
|
||||
if not backup.can_restore_website(site):
|
||||
if not available_website_restore_targets(backup):
|
||||
raise Http404
|
||||
return backup
|
||||
|
||||
def get_form_kwargs(self):
|
||||
return super().get_form_kwargs() | {
|
||||
"targets": available_website_restore_targets(self.backup)
|
||||
}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
targets = available_website_restore_targets(self.backup)
|
||||
return super().get_context_data(
|
||||
restore_site=next(iter(targets.values()))
|
||||
if len(targets) == 1
|
||||
else None,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def queue_restore(self, backup, data, operator_username):
|
||||
queue_website_restore(
|
||||
backup,
|
||||
@@ -1207,6 +1241,7 @@ class RequestWebsiteRestore(BackupRestoreView):
|
||||
filename=data["filename"],
|
||||
replace=data["replace"],
|
||||
operator_username=operator_username,
|
||||
site_key=data.get("site_key"),
|
||||
)
|
||||
|
||||
|
||||
@@ -1994,6 +2029,7 @@ class HostingPlanEditor:
|
||||
fields = (
|
||||
"name",
|
||||
"description",
|
||||
"website_limit",
|
||||
"database_limit",
|
||||
"mailbox_limit",
|
||||
"mailbox_quota_mib",
|
||||
@@ -2009,6 +2045,15 @@ class HostingPlanEditor:
|
||||
template_name = "hosting/hosting_plan_form.html"
|
||||
success_url = reverse_lazy("panel:hosting_plans")
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
if "data" in kwargs and "website_limit" not in kwargs["data"]:
|
||||
data = kwargs["data"].copy()
|
||||
instance = kwargs.get("instance")
|
||||
data["website_limit"] = instance.website_limit if instance else 1
|
||||
kwargs["data"] = data
|
||||
return kwargs
|
||||
|
||||
|
||||
class HostingPlanCreate(
|
||||
OperatorOnlyMixin, PermissionRequiredMixin, HostingPlanEditor, CreateView
|
||||
|
||||
+41
-17
@@ -16,6 +16,7 @@ from .php_runtime import validate_php_version, validate_php_versions
|
||||
from .service_access import ServiceAccessRequest, parse_service_request
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
INDEPENDENT_SITE_VERSION = 2
|
||||
MAX_STORAGE_BYTES = 2**63 - 1
|
||||
MAX_STORAGE_LIMIT_MIB = 2**31 - 1
|
||||
CONFIGURATIONS = {
|
||||
@@ -28,6 +29,7 @@ CONFIGURATIONS = {
|
||||
class WebSite:
|
||||
account_id: int
|
||||
domain: str
|
||||
site_id: int | None = None
|
||||
|
||||
def __post_init__(self):
|
||||
if (
|
||||
@@ -37,40 +39,62 @@ class WebSite:
|
||||
raise ValueError(
|
||||
"The account ID must be a positive 64-bit integer."
|
||||
)
|
||||
if self.site_id is not None and (
|
||||
type(self.site_id) is not int or not 1 <= self.site_id <= 2**63 - 1
|
||||
):
|
||||
raise ValueError("The site ID must be a positive 64-bit integer.")
|
||||
if not isinstance(self.domain, str):
|
||||
raise ValueError("The domain must be a string.")
|
||||
object.__setattr__(self, "domain", canonical_domain(self.domain))
|
||||
|
||||
@property
|
||||
def node_key(self):
|
||||
return (
|
||||
str(self.account_id)
|
||||
if self.site_id is None
|
||||
else f"s{self.site_id}"
|
||||
)
|
||||
|
||||
@property
|
||||
def service_user(self):
|
||||
return f"coulobre-{self.node_key}"
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
if not isinstance(data, dict) or data.keys() != {
|
||||
"version",
|
||||
"account_id",
|
||||
"domain",
|
||||
}:
|
||||
raise ValueError(
|
||||
"Expected a manifest with version, account_id, and domain."
|
||||
)
|
||||
version = data["version"]
|
||||
if type(version) is not int or version != MANIFEST_VERSION:
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Expected a website manifest.")
|
||||
version = data.get("version")
|
||||
if type(version) is not int or version not in (
|
||||
MANIFEST_VERSION,
|
||||
INDEPENDENT_SITE_VERSION,
|
||||
):
|
||||
raise ValueError("Unsupported web deployment manifest version.")
|
||||
return cls(data["account_id"], data["domain"])
|
||||
fields = {"version", "account_id", "domain"}
|
||||
if version == INDEPENDENT_SITE_VERSION:
|
||||
fields.add("site_id")
|
||||
if data.keys() != fields or (
|
||||
version == INDEPENDENT_SITE_VERSION and data["site_id"] is None
|
||||
):
|
||||
raise ValueError("Expected a website manifest.")
|
||||
return cls(data["account_id"], data["domain"], data.get("site_id"))
|
||||
|
||||
def manifest(self):
|
||||
return {
|
||||
data = {
|
||||
"version": MANIFEST_VERSION,
|
||||
"account_id": self.account_id,
|
||||
"domain": self.domain,
|
||||
}
|
||||
if self.site_id is not None:
|
||||
data.update(version=INDEPENDENT_SITE_VERSION, site_id=self.site_id)
|
||||
return data
|
||||
|
||||
def configuration(self):
|
||||
service_user = f"coulobre-{self.account_id}"
|
||||
return {
|
||||
"account_id": self.account_id,
|
||||
"domain": self.domain,
|
||||
"service_user": service_user,
|
||||
"document_root": f"/srv/coulobre/web/{self.account_id}/public",
|
||||
"socket_path": f"/run/php/{service_user}.sock",
|
||||
"service_user": self.service_user,
|
||||
"document_root": f"/srv/coulobre/web/{self.node_key}/public",
|
||||
"socket_path": f"/run/php/{self.service_user}.sock",
|
||||
}
|
||||
|
||||
def render(
|
||||
@@ -119,7 +143,7 @@ class WebAlias:
|
||||
@property
|
||||
def name(self):
|
||||
suffix = sha256(self.domain.encode("ascii")).hexdigest()[:24]
|
||||
return f"coulobre-{self.site.account_id}-alias-{suffix}"
|
||||
return f"{self.site.service_user}-alias-{suffix}"
|
||||
|
||||
@classmethod
|
||||
def from_manifest(cls, data):
|
||||
|
||||
@@ -9,6 +9,14 @@ APACHE_CONFIG = Path("/etc/apache2/conf-enabled")
|
||||
SSH_CONFIG = Path("/etc/ssh/sshd_config.d")
|
||||
|
||||
|
||||
def website_suspension_path(site):
|
||||
return APACHE_CONFIG / f"coulobre-suspended-{site.node_key}.conf"
|
||||
|
||||
|
||||
def sftp_suspension_path(site):
|
||||
return SSH_CONFIG / f"01-coulobre-suspended-{site.node_key}.conf"
|
||||
|
||||
|
||||
def set_website_access(site, suspended):
|
||||
document_root = site.configuration()["document_root"]
|
||||
# The shared ACME webroot is outside the hosted document root.
|
||||
@@ -17,17 +25,24 @@ def set_website_access(site, suspended):
|
||||
" Require all denied\n"
|
||||
"</DirectoryMatch>\n"
|
||||
)
|
||||
path = APACHE_CONFIG / f"coulobre-suspended-{site.account_id}.conf"
|
||||
path = website_suspension_path(site)
|
||||
|
||||
def validate():
|
||||
web.run("/usr/sbin/apache2ctl", "configtest")
|
||||
|
||||
set_configuration(site, suspended, path, config, validate, "apache2")
|
||||
if site.site_id is not None:
|
||||
from .web_node_sftp import AUTHORIZED_KEYS
|
||||
|
||||
if os.path.lexists(
|
||||
AUTHORIZED_KEYS / site.service_user
|
||||
) or os.path.lexists(sftp_suspension_path(site)):
|
||||
set_sftp_access(site, suspended)
|
||||
|
||||
|
||||
def set_sftp_access(site, suspended):
|
||||
user = site.configuration()["service_user"]
|
||||
path = SSH_CONFIG / f"01-coulobre-suspended-{site.account_id}.conf"
|
||||
path = sftp_suspension_path(site)
|
||||
|
||||
def validate():
|
||||
configuration = web.run(
|
||||
|
||||
@@ -54,7 +54,7 @@ class SitePaths:
|
||||
def for_site(cls, site, *, version=None, archived_account=None):
|
||||
configuration = site.configuration()
|
||||
name = configuration["service_user"]
|
||||
account = WEB_ROOT / str(site.account_id)
|
||||
account = WEB_ROOT / site.node_key
|
||||
socket = Path(configuration["socket_path"])
|
||||
runtime = DEFAULT_PHP_RUNTIME
|
||||
route = (archived_account or account) / ".coulobre-php.sock"
|
||||
@@ -132,7 +132,7 @@ def install_site(site, *, php_settings=None, allowed=()):
|
||||
create_route = not (
|
||||
paths.routed
|
||||
or (
|
||||
os.path.lexists(STATE_DIRECTORY / f"{site.account_id}.json")
|
||||
os.path.lexists(STATE_DIRECTORY / f"{site.node_key}.json")
|
||||
and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool))
|
||||
)
|
||||
)
|
||||
@@ -171,7 +171,7 @@ def site_status(site):
|
||||
require_root_directory(STATE_DIRECTORY)
|
||||
except FileNotFoundError:
|
||||
return report
|
||||
marker = STATE_DIRECTORY / f"{site.account_id}.json"
|
||||
marker = STATE_DIRECTORY / f"{site.node_key}.json"
|
||||
if not os.path.lexists(marker):
|
||||
return report
|
||||
|
||||
@@ -195,7 +195,7 @@ def site_status(site):
|
||||
|
||||
|
||||
def check_reservation(site):
|
||||
marker = STATE_DIRECTORY / f"{site.account_id}.json"
|
||||
marker = STATE_DIRECTORY / f"{site.node_key}.json"
|
||||
try:
|
||||
saved = json.loads(read_root_file(marker))
|
||||
except FileNotFoundError:
|
||||
@@ -208,7 +208,7 @@ def check_reservation(site):
|
||||
|
||||
def site_storage(site):
|
||||
check_reservation(site)
|
||||
account = WEB_ROOT / str(site.account_id)
|
||||
account = WEB_ROOT / site.node_key
|
||||
require_root_directory(account)
|
||||
user = site.configuration()["service_user"]
|
||||
uid, gid = check_system_account(user, account)
|
||||
@@ -254,7 +254,7 @@ def check_services(runtime):
|
||||
|
||||
|
||||
def reserve_account(site, user, paths):
|
||||
marker = STATE_DIRECTORY / f"{site.account_id}.json"
|
||||
marker = STATE_DIRECTORY / f"{site.node_key}.json"
|
||||
if os.path.lexists(marker.with_suffix(".retired")):
|
||||
raise ValueError("This website belongs to a retired hosting account.")
|
||||
manifest = site.manifest()
|
||||
@@ -263,7 +263,7 @@ def reserve_account(site, user, paths):
|
||||
if existing == marker:
|
||||
if saved != manifest:
|
||||
raise ValueError(
|
||||
"The account is already reserved with a different "
|
||||
"The website is already reserved with a different "
|
||||
"manifest."
|
||||
)
|
||||
elif saved["domain"] == site.domain:
|
||||
@@ -271,7 +271,10 @@ def reserve_account(site, user, paths):
|
||||
"The primary domain is already reserved by another account."
|
||||
)
|
||||
|
||||
from .web_node_aliases import check_alias_domain_available
|
||||
from .web_node_aliases import (
|
||||
check_alias_domain_available,
|
||||
check_apache_hostname_available,
|
||||
)
|
||||
|
||||
check_alias_domain_available(site.domain)
|
||||
|
||||
@@ -285,6 +288,8 @@ def reserve_account(site, user, paths):
|
||||
raise ValueError(
|
||||
"The web node already has unmanaged resources for this account."
|
||||
)
|
||||
if site.site_id is not None:
|
||||
check_apache_hostname_available(site.domain)
|
||||
write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600)
|
||||
|
||||
|
||||
|
||||
@@ -30,14 +30,21 @@ def retire_site(request):
|
||||
retirement = RetirementRecord(web.STATE_DIRECTORY, request)
|
||||
if retirement.is_complete:
|
||||
return
|
||||
reservation = web.STATE_DIRECTORY / f"{site.account_id}.json"
|
||||
reservation = web.STATE_DIRECTORY / f"{site.node_key}.json"
|
||||
started = retirement.matches(retirement.started)
|
||||
if (
|
||||
site.site_id is not None
|
||||
and not os.path.lexists(reservation)
|
||||
and not (retirement.directory / "site").is_file()
|
||||
):
|
||||
retire_unprovisioned_site(site, reservation, retirement)
|
||||
return
|
||||
if os.path.lexists(reservation) or not started:
|
||||
web.check_reservation(site)
|
||||
elif not (retirement.directory / "site").is_file():
|
||||
raise ValueError("The original website reservation is missing.")
|
||||
archived_account = web.WEB_ROOT / ".retired" / request.operation_id
|
||||
account = web.WEB_ROOT / str(site.account_id)
|
||||
account = web.WEB_ROOT / site.node_key
|
||||
paths = web.SitePaths.for_site(
|
||||
site,
|
||||
archived_account=archived_account
|
||||
@@ -67,13 +74,45 @@ def retire_site(request):
|
||||
apache = managed_vhosts(site, paths)
|
||||
retirement.begin()
|
||||
detach_site(site, paths, key_file, apache, retirement)
|
||||
marker = reservation.with_suffix(".retired")
|
||||
if not os.path.lexists(marker):
|
||||
write_new_file(marker, retirement.document, mode=0o600)
|
||||
elif read_root_file(marker, mode=0o600) != retirement.document:
|
||||
raise ValueError("The website has a different retirement record.")
|
||||
archive_path(reservation, retirement.directory / "site")
|
||||
retirement.finish()
|
||||
finish_site_retirement(reservation, retirement)
|
||||
|
||||
|
||||
def retire_unprovisioned_site(site, reservation, retirement):
|
||||
paths = web.SitePaths.for_site(site)
|
||||
https, enabled = https_paths(paths)
|
||||
if (
|
||||
web.current_user(site.service_user)
|
||||
or web.current_group(site.service_user)
|
||||
or any(
|
||||
os.path.lexists(path)
|
||||
for path in (
|
||||
paths.account,
|
||||
paths.apache,
|
||||
paths.enabled,
|
||||
paths.pool,
|
||||
paths.socket,
|
||||
https,
|
||||
enabled,
|
||||
AUTHORIZED_KEYS / site.service_user,
|
||||
)
|
||||
)
|
||||
):
|
||||
raise ValueError(
|
||||
"The web node has unmanaged resources for this website."
|
||||
)
|
||||
check_aliases(site)
|
||||
retirement.begin()
|
||||
finish_site_retirement(reservation, retirement)
|
||||
|
||||
|
||||
def finish_site_retirement(reservation, retirement):
|
||||
marker = reservation.with_suffix(".retired")
|
||||
if not os.path.lexists(marker):
|
||||
write_new_file(marker, retirement.document, mode=0o600)
|
||||
elif read_root_file(marker, mode=0o600) != retirement.document:
|
||||
raise ValueError("The website has a different retirement record.")
|
||||
archive_path(reservation, retirement.directory / "site")
|
||||
retirement.finish()
|
||||
|
||||
|
||||
def check_aliases(site):
|
||||
@@ -82,8 +121,7 @@ def check_aliases(site):
|
||||
return
|
||||
require_root_directory(directory)
|
||||
if any(
|
||||
read_alias(marker).site.account_id == site.account_id
|
||||
for marker in directory.glob("*.json")
|
||||
read_alias(marker).site == site for marker in directory.glob("*.json")
|
||||
):
|
||||
raise ValueError(
|
||||
"Remove the managed website aliases before retiring the site."
|
||||
|
||||
@@ -32,7 +32,7 @@ def switch_php_version(site, version):
|
||||
raise ValueError(
|
||||
f"Install stable PHP {version} FPM on the web node."
|
||||
)
|
||||
if current.socket.name == f"coulobre-{site.account_id}.sock" and (
|
||||
if current.socket.name == f"{site.service_user}.sock" and (
|
||||
current.routed or current.runtime.version != version
|
||||
):
|
||||
current = route_legacy_site(site, current)
|
||||
|
||||
@@ -37,6 +37,13 @@ def apply_sftp_keys(request):
|
||||
target = AUTHORIZED_KEYS / user
|
||||
|
||||
with locked_web_node(fcntl.LOCK_EX):
|
||||
if site.site_id is not None:
|
||||
from .web_node_access import website_suspension_path
|
||||
|
||||
if os.path.lexists(website_suspension_path(site)):
|
||||
raise ValueError(
|
||||
"Resume the website before changing SFTP keys."
|
||||
)
|
||||
check_reservation(site)
|
||||
if os.path.lexists(target):
|
||||
check_root_file(target, mode=0o644)
|
||||
|
||||
@@ -158,11 +158,7 @@ def https_paths(paths):
|
||||
|
||||
|
||||
def certbot_lineage(site):
|
||||
name = (
|
||||
site.name
|
||||
if isinstance(site, WebAlias)
|
||||
else f"coulobre-{site.account_id}"
|
||||
)
|
||||
name = site.name if isinstance(site, WebAlias) else site.service_user
|
||||
return CERTBOT_ROOT / "live" / name
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user