diff --git a/deploy/systemd/coulobre-directadmin-import-worker.service b/deploy/systemd/coulobre-directadmin-import-worker.service index d72eb45..bee13d4 100644 --- a/deploy/systemd/coulobre-directadmin-import-worker.service +++ b/deploy/systemd/coulobre-directadmin-import-worker.service @@ -9,7 +9,8 @@ Type=exec User=coulobre-panel Group=coulobre-panel SupplementaryGroups=coulobre-mail-provisioning -ReadWritePaths=-/var/lib/coulobre-panel-imports +StateDirectory=coulobre-panel-imports +StateDirectoryMode=0700 EnvironmentFile=/etc/coulobre/panel.env WorkingDirectory=/opt/coulobre UMask=0077 diff --git a/deploy/systemd/coulobre-panel.service.d/import-storage.conf b/deploy/systemd/coulobre-panel.service.d/import-storage.conf new file mode 100644 index 0000000..42ea9a7 --- /dev/null +++ b/deploy/systemd/coulobre-panel.service.d/import-storage.conf @@ -0,0 +1,3 @@ +[Service] +StateDirectory=coulobre-panel-imports +StateDirectoryMode=0700 diff --git a/docs/deployment.md b/docs/deployment.md index 33aaebf..a12c3b5 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1534,9 +1534,11 @@ not modify or promote the live site. ### Import WordPress from a ZIP or TAR export -New installer-managed panels already have a private WordPress upload inbox. -APT and web upgrades preserve the installed panel unit. If you are enabling -imports on an upgraded panel and the unit does not list +New installer-managed panels have a private upload inbox for WordPress and +DirectAdmin imports. Starting with Core 1.10, APT upgrades supply the inbox +through a systemd drop-in without replacing local unit overrides. For a +manual or source archive upgrade, or if you override the inbox locally, +check the effective unit. If it does not list `coulobre-panel-imports` in `systemctl show -p StateDirectory coulobre-panel.service`, add the inbox with `sudo systemctl edit coulobre-panel.service`: diff --git a/docs/development.md b/docs/development.md index a5744e4..c35ee32 100644 --- a/docs/development.md +++ b/docs/development.md @@ -736,9 +736,11 @@ domain has only one web root, Coulobre uses it. You can restore all supported components or only what you need. Select a package with enough website slots when restoring more than one site. The destination can be a new hosting account or an existing empty account -whose primary domain exactly matches. Remove any existing starter page -before restoring website files. Existing DNS can be left in place if you -do not select DNS import. New accounts do not include a new customer login. +whose primary domain exactly matches. A document root containing only an +unchanged Coulobre starter page counts as empty. A modified starter page +or any other file blocks the website restore. Existing DNS can be left in +place if you do not select DNS import. New accounts do not include a new +customer login. Open the destination account after import to attach a customer or manager. The selected component types apply to supported content across the selected diff --git a/docs/panel-design.md b/docs/panel-design.md index a097359..006ac93 100644 --- a/docs/panel-design.md +++ b/docs/panel-design.md @@ -93,7 +93,9 @@ heading, help, fields, and actions should share a left edge. workflow. Keep the final destructive confirmation visually distinct. - Keep a record name and its secondary identifier in one table cell. Use a wrapping row when space permits, and omit the identifier when it repeats - the name. The record name remains the link. + the name. The record name remains the link. The local and cluster + hosting inventories use a separate, right-aligned **Primary domain** + column immediately before **Status** for easy comparison. - Group table actions in a wrapping `.table-actions` container. Center them vertically within the row and allow labels to wrap instead of widening the whole table. Keep overflow within `.table-scroll`. @@ -135,6 +137,21 @@ Django's label association, error state, and description IDs. ``` +### Action feedback + +Use Django messages for the immediate outcome of signed-in actions. +The shared shell displays them as dismissible notifications with JavaScript +and in the page flow without it. Distinguish **queued** from **complete**. +Keep validation next to the relevant field and show a clear summary near +the start of long forms. Don't make notifications the only place to find +errors, progress, or recovery instructions. + +Live regions may opt in to a notification on a meaningful state transition +using `data-live-state`, `data-live-notice` and an optional +`data-live-notice-level`. Notify only once for a transition, not for each +poll. Keep server or cluster announcements and impersonation indicators +in the page. + ### Dependent operations Show a blocked prerequisite beside the resource that needs it. Put the @@ -148,6 +165,12 @@ the source and destination, show the snapshot totals first, and put the per-folder or per-item breakdown below. Label partial counts and missing estimates explicitly. Distinguish the full source inventory from work remaining after a checkpoint. Do not display credentials or source content. +Distinguish a matching existing account from a requested new account by +name and domain. Show new-account settings only for that choice when +JavaScript is available, and validate both paths on the server. Keep +the selected destination visible while a job is queued. Results separate +completed, unconfirmed, and unrequested work, with links to review or finish +setup. For selective imports, put editable choices below the inventory and keep them outside auto-refreshing status regions. State explicitly which choices affect the destination, which are skipped and whether failures can leave diff --git a/pyproject.toml b/pyproject.toml index ffcabe0..263a672 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "coulobre-panel" -version = "1.9.0" +version = "1.10.0" description = "A web hosting control panel for hosting providers and resellers." readme = "README.md" requires-python = ">=3.12" diff --git a/src/coulobre/hosting/directadmin_web_import.py b/src/coulobre/hosting/directadmin_web_import.py index 33ed2de..d0727cc 100644 --- a/src/coulobre/hosting/directadmin_web_import.py +++ b/src/coulobre/hosting/directadmin_web_import.py @@ -1,7 +1,9 @@ """Stage and inspect DirectAdmin archives for operator approval.""" +import errno import fcntl import hashlib +import logging import os import stat from datetime import timedelta @@ -146,9 +148,19 @@ def register_upload(upload, actor): except Exception: path.unlink(missing_ok=True) raise - except OSError: + except OSError as error: + logging.getLogger(__name__).warning( + "DirectAdmin archive staging failed (errno %s).", error.errno + ) + if error.errno in {errno.ENOSPC, errno.EDQUOT}: + detail = "Free space in the panel's import storage and try again." + else: + detail = ( + "Check the panel service's private import storage. " + "Inspect its StateDirectory and journal before retrying." + ) raise ValidationError( - "Could not stage the archive. Check server storage." + f"Could not stage the archive. {detail}" ) from None return job @@ -540,7 +552,10 @@ def confirm_import(job_id, actor, selection): validate_extra_domains(selection, account, job.report) plan = plan_for_import(account, selection) validate_quotas(job.report, account, selection, plan) - job.selection = selection | {"account_id": getattr(account, "pk", None)} + job.selection = selection | { + "account_id": getattr(account, "pk", None), + "destination_name": account.name if account else selection["name"], + } job.state = "import_queued" job.confirmed_by = actor job.started_at = None diff --git a/src/coulobre/hosting/directadmin_web_tasks.py b/src/coulobre/hosting/directadmin_web_tasks.py index 008903b..0a8f62e 100644 --- a/src/coulobre/hosting/directadmin_web_tasks.py +++ b/src/coulobre/hosting/directadmin_web_tasks.py @@ -271,13 +271,20 @@ def restore_components(job): f"{item['label']} is no longer provisioned." ) if item["kind"] != "mail" or item["messages"]: - restore_directadmin_component( + receipt = restore_directadmin_component( item["kind"], destination_spec(job, item), archive_path(job.pk), source=item.get("source", ""), digest=job.digest, ) + if isinstance(receipt, dict): + item["receipt"] = { + field: receipt[field] + for field in ("files", "bytes", "messages") + if type(receipt.get(field)) is int + and receipt[field] >= 0 + } item["status"] = ( "Mailbox configured (no source messages)" if item["kind"] == "mail" and not item["messages"] diff --git a/src/coulobre/hosting/directadmin_web_views.py b/src/coulobre/hosting/directadmin_web_views.py index a540b3e..6f87a36 100644 --- a/src/coulobre/hosting/directadmin_web_views.py +++ b/src/coulobre/hosting/directadmin_web_views.py @@ -1,4 +1,5 @@ from django import forms +from django.contrib import messages from django.core.exceptions import ValidationError from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone @@ -37,6 +38,8 @@ class DirectAdminSelectionForm(forms.Form): ) target = forms.ChoiceField( label="Destination", + widget=forms.RadioSelect, + initial="new", choices=( ("new", "Create a hosting account"), ("existing", "Use the matching empty hosting account"), @@ -78,6 +81,13 @@ class DirectAdminSelectionForm(forms.Form): def __init__(self, report, *args, **kwargs): super().__init__(*args, **kwargs) self.report = report + if ( + self.is_bound + and self.data.get(self.add_prefix("target")) == "existing" + ): + self.data = self.data.copy() + for field in ("hosting_plan", "name"): + self.data.pop(self.add_prefix(field), None) choices = [ (entry["name"], entry["name"]) for entry in report["domains"] ] @@ -131,7 +141,11 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): except ValidationError as error: form.add_error("archive", error) else: + messages.success(request, "DirectAdmin preflight queued.") return redirect("panel:directadmin_import", pk=job.pk) + messages.error( + request, "Preflight not queued. Check the upload below." + ) return self.page(form=form, status=400) job = get_object_or_404(DirectAdminWebImport, pk=pk) @@ -146,6 +160,7 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): report={}, ): archive_path(pk).unlink(missing_ok=True) + messages.info(request, "DirectAdmin upload discarded.") return redirect("panel:directadmin_import", pk=pk) form = DirectAdminSelectionForm(job.report, request.POST) if form.is_valid(): @@ -154,7 +169,11 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): except ValidationError as error: form.add_error(None, error) else: + messages.success(request, "DirectAdmin import queued.") return redirect("panel:directadmin_import", pk=pk) + messages.error( + request, "Import not queued. Review the highlighted details." + ) return self.page(job, form, status=400) def page(self, job=None, form=None, status=200): @@ -163,12 +182,24 @@ class DirectAdminImportView(OperatorOnlyMixin, OperatorAuthorization, View): form = DirectAdminArchiveForm() elif job.state == "review" and job.expires_at > timezone.now(): form = DirectAdminSelectionForm(job.report) + components = set(job.selection.get("components", ())) if job else set() + choices = DirectAdminSelectionForm.base_fields["components"].choices return render( self.request, self.template_name, { "job": job, "form": form, + "not_started": [ + label for key, label in choices if key in components + ] + if job and job.finished_at and not job.work + else (), + "not_selected": [ + label + for key, label in choices + if components and key not in components + ], "pending": job is not None and job.state in ACTIVE_STATES, "recent": DirectAdminWebImport.objects.select_related( "account" diff --git a/src/coulobre/hosting/static/hosting/directadmin-import.js b/src/coulobre/hosting/static/hosting/directadmin-import.js new file mode 100644 index 0000000..ba255de --- /dev/null +++ b/src/coulobre/hosting/static/hosting/directadmin-import.js @@ -0,0 +1,22 @@ +"use strict"; + +const importForm = document.querySelector("[data-directadmin-review]"); + +if (importForm) { + const domain = importForm.elements.domain; + const destination = importForm.elements.target; + const newFields = importForm.querySelector("[data-import-new]"); + const matches = [...importForm.querySelectorAll("[data-import-match]")]; + + function updateDestination() { + const existing = destination.value === "existing"; + newFields.hidden = existing; + newFields.disabled = existing; + for (const match of matches) { + match.hidden = !existing || match.dataset.importMatch !== domain.value; + } + } + + importForm.addEventListener("change", updateDestination); + updateDestination(); +} diff --git a/src/coulobre/hosting/static/hosting/panel-live-status.js b/src/coulobre/hosting/static/hosting/panel-live-status.js index fab3f1a..501603e 100644 --- a/src/coulobre/hosting/static/hosting/panel-live-status.js +++ b/src/coulobre/hosting/static/hosting/panel-live-status.js @@ -43,6 +43,18 @@ async function refreshStatus() { for (const detail of next.querySelectorAll("details[data-live-detail]")) { detail.open = openDetails.has(detail.dataset.liveDetail); } + const stateChanged = region.dataset.liveState !== next.dataset.liveState; + if (next.dataset.liveState) { + region.dataset.liveState = next.dataset.liveState; + } + if (stateChanged && next.dataset.liveNotice) { + document.dispatchEvent(new CustomEvent("coulobre:status-changed", { + detail: { + message: next.dataset.liveNotice, + level: next.dataset.liveNoticeLevel || "info", + }, + })); + } if (region.innerHTML === next.innerHTML) { continue; } diff --git a/src/coulobre/hosting/static/hosting/panel-notifications.js b/src/coulobre/hosting/static/hosting/panel-notifications.js new file mode 100644 index 0000000..d0bb078 --- /dev/null +++ b/src/coulobre/hosting/static/hosting/panel-notifications.js @@ -0,0 +1,37 @@ +"use strict"; + +const notificationStack = document.querySelector("[data-panel-notifications]"); + +if (notificationStack) { + notificationStack.classList.add("panel-notifications-floating"); + + function enhanceNotification(notice) { + const dismiss = document.createElement("button"); + dismiss.type = "button"; + dismiss.className = "button secondary compact"; + dismiss.textContent = "Dismiss"; + dismiss.setAttribute("aria-label", "Dismiss notification"); + dismiss.addEventListener("click", () => { + const next = notice.nextElementSibling || notice.previousElementSibling; + notice.remove(); + (next?.querySelector("button") || document.getElementById("main-content")).focus(); + }); + notice.append(dismiss); + } + + notificationStack.querySelectorAll(".panel-notification").forEach(enhanceNotification); + + document.addEventListener("coulobre:status-changed", event => { + const {message, level} = event.detail; + const notice = document.createElement("div"); + notice.className = "notice panel-notification"; + notice.dataset.notificationLevel = level; + const content = document.createElement("p"); + content.setAttribute("role", level === "error" ? "alert" : "status"); + notice.append(content); + enhanceNotification(notice); + notificationStack.append(notice); + // Add the text after the live region is mounted. + requestAnimationFrame(() => { content.textContent = message; }); + }); +} diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index a0aea73..9ff9932 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -719,16 +719,13 @@ h3, h4, h5, h6 { flex: 1 1 25rem; } -.account-identity { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0.15rem 0.65rem; +.account-identity, .cell-primary-domain { + overflow-wrap: anywhere; } -.account-identity > * { - min-width: 0; - overflow-wrap: anywhere; +th.cell-primary-domain, td.cell-primary-domain { + text-align: end; + width: 22%; } .account-heading-meta { @@ -838,6 +835,7 @@ input::placeholder { } .table-scroll { + position: relative; overflow-x: auto; } @@ -1595,3 +1593,50 @@ fieldset > div:has(> div > label > input:is([type="checkbox"], [type="radio"])) min-inline-size: 0; grid-template-rows: auto auto 1fr auto; } + +.panel-notifications:not(:has(.panel-notification)) { + display: none; +} + +.panel-notifications-floating { + position: fixed; + inset-block-start: 1rem; + inset-inline-end: 1rem; + width: min(27rem, calc(100vw - 2rem)); + max-height: 45vh; + overflow: auto; + z-index: 20; + display: grid; + gap: 0.45rem; +} + +.panel-notification { + display: flex; + align-items: start; + justify-content: space-between; + gap: 0.75rem; + overflow-wrap: anywhere; +} + +.panel-notifications-floating .panel-notification { + margin: 0; + border-radius: 0.4rem; + padding: 0.65rem 0.8rem; +} + +.panel-notification p { + margin: 0; +} + +.panel-notification[data-notification-level="error"] { + border-color: var(--invalid); + background-color: var(--error-bg); +} + +.panel-notification[data-notification-level="warning"] { + background-color: var(--warning-bg); +} + +[data-import-new][hidden] { + display: none; +} diff --git a/src/coulobre/hosting/templates/hosting/account_backups.html b/src/coulobre/hosting/templates/hosting/account_backups.html index ee37539..93a1d99 100644 --- a/src/coulobre/hosting/templates/hosting/account_backups.html +++ b/src/coulobre/hosting/templates/hosting/account_backups.html @@ -35,7 +35,7 @@ {% endif %} -
Type the primary domain to confirm this preview.
{% csrf_token %} {{ form.as_div }} - + {% endif %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index d0dc29f..d0c1a65 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -93,10 +93,14 @@ {% endif %} {% for announcement in panel_announcements %}| Account | Hosting node | Status | ||||
|---|---|---|---|---|---|---|
| Account | Hosting node | Primary domain | Status | |||
| {% include "hosting/account_identity.html" with account_url=account.url name=account.name primary_domain=account.primary_domain only %} | +{% include "hosting/account_identity.html" with account_url=account.url name=account.name only %} | {% include "hosting/hosting_node.html" with node=page.node only %} | + {% include "hosting/account_primary_domain.html" with name=account.name primary_domain=account.primary_domain only %}{% include "hosting/account_status.html" %} | |||
| No matching accounts on {{ page.node.label }}{% if previous_offset is not None %} on this page{% endif %}. | +No matching accounts on {{ page.node.label }}{% if previous_offset is not None %} on this page{% endif %}. | |||||
| View all results on {{ page.node.label }} | ||||||
| View all results on {{ page.node.label }} | ||||||
| Requested | Destination | Status | |||
|---|---|---|---|---|---|
| Requested | Destination | Status | Actions | ||
| {{ previous.requested_at|date:"j M Y, H:i T" }} | -{{ previous.account|default:"Not selected" }} | +{{ previous.requested_at|date:"j M Y, H:i T" }} | ++ {% if previous.selection.domain %} + {{ previous.selection.domain }}{% if previous.selection.destination_name and previous.selection.destination_name != previous.selection.domain %} · {{ previous.selection.destination_name }}{% endif %} + {% else %}Not selected{% endif %} + | {{ previous.get_state_display }} | ++ {% if previous.state == "review" %}Review preflight{% elif previous.finished_at %}View import result{% else %}View import progress{% endif %} + |
Destination · {{ job.selection.domain }}{% if job.selection.destination_name and job.selection.destination_name != job.selection.domain %} · {{ job.selection.destination_name }}{% endif %}
+ {% endif %} {% if pending %}{% if job.state == "inspect_queued" or job.state == "inspecting" %} @@ -56,17 +76,21 @@ {% if job.work %}
Changes already applied are not undone. Check the destination and the component status below.
{% endif %} {% elif job.state == "complete" %}Review the imported data before updating DNS. Existing public DNS and the source account were not changed.
+ {% if "dns" in job.selection.components and job.account %}{% endif %} {% endif %} {% if job.work %}| Component | Destination | State |
|---|---|---|
| {{ item.kind|capfirst }} | {{ item.label }} | {{ item.status|default:"Waiting" }} |
| {{ item.kind|capfirst }} | {{ item.label }} | {% if item.status %}{{ item.status }}{% elif job.finished_at %}Not completed{% else %}Waiting{% endif %}
+ {% if item.receipt %} {% if "files" in item.receipt %}{{ item.receipt.files }} files{% elif "messages" in item.receipt %}{{ item.receipt.messages }} messages{% endif %}{% if "bytes" in item.receipt %}{% if "files" in item.receipt or "messages" in item.receipt %} · {% endif %}{{ item.receipt.bytes|filesizeformat }}{% endif %} {% endif %} |
Not started · {{ not_started|join:", " }}
{% endif %} + {% if not_selected and job.finished_at %}Not requested · {{ not_selected|join:", " }}
{% endif %}Source account {{ job.report.username }} · {{ job.size|filesizeformat }} upload. Choose a primary domain and any additional domains to restore. Database dumps belong to the whole source account.
{% for domain in job.report.domains %}Some database dumps have unsupported names or are empty or duplicated. They are not imported.
{% endif %} {% if job.report.home_archive %}Nested home archives are not imported.
{% endif %} - {% if job.report.skipped_non_regular_entries %}The archive contains {{ job.report.skipped_non_regular_entries }} links or special entries. Selected website or mail files containing unsupported entries may be rejected.
{% endif %} + {% if job.report.skipped_non_regular_entries %}The archive contains unsupported links or special entries ({{ job.report.skipped_non_regular_entries }}). Website or mail components containing them may be rejected.
{% endif %}{{ topology.problem }}
{% endif %}{{ problem }}
{% endif %} {% if not job or job.problem and not job.remove %} -Checking the source and destination. Nothing is being copied.
diff --git a/src/coulobre/hosting/templates/hosting/operator_backups.html b/src/coulobre/hosting/templates/hosting/operator_backups.html index fe6e1c2..346f13c 100644 --- a/src/coulobre/hosting/templates/hosting/operator_backups.html +++ b/src/coulobre/hosting/templates/hosting/operator_backups.html @@ -24,7 +24,7 @@ {% if enabled %}{{ message }}
+The archive contains local service configuration, MariaDB, and hosted files and mail. Retrieve it on the server using an administrator account.
Enable system backups and the local operator worker on this server.
{% endif %} diff --git a/src/coulobre/hosting/templates/hosting/website_files.html b/src/coulobre/hosting/templates/hosting/website_files.html index 448e522..4ad9686 100644 --- a/src/coulobre/hosting/templates/hosting/website_files.html +++ b/src/coulobre/hosting/templates/hosting/website_files.html @@ -25,13 +25,13 @@ {% csrf_token %} {{ upload_form.as_div }} - +{{ message }}
- {% endfor %} - {% endif %} {% block page_content %}{% endblock %} {% endblock %} diff --git a/src/coulobre/hosting/test_directadmin_web_import.py b/src/coulobre/hosting/test_directadmin_web_import.py index 1cb0cf5..761560e 100644 --- a/src/coulobre/hosting/test_directadmin_web_import.py +++ b/src/coulobre/hosting/test_directadmin_web_import.py @@ -139,7 +139,7 @@ class DirectAdminWebImportTests(TestCase): response = self.client.get(url) self.assertContains(response, "source_main") self.assertContains(response, "info@example.net") - self.assertContains(response, "1 messages") + self.assertContains(response, "1 message · 1 folder with messages") self.assertContains(response, "6 DNS records") self.assertNotContains(response, "should-never-be-stored") self.assertNotIn("should-never-be-stored", str(job.report)) @@ -156,7 +156,16 @@ class DirectAdminWebImportTests(TestCase): name="Destination", primary_domain=DOMAIN ) job, url = self.prepare() - self.assertEqual(self.submit(url, target="existing").status_code, 302) + review = self.client.get(url) + self.assertContains(review, "Use the matching empty hosting account") + self.assertContains(review, "New account settings") + response = self.submit( + url, target="existing", hosting_plan="invalid", name="unused" + ) + self.assertEqual(response.status_code, 302) + queued = self.client.get(self.url) + self.assertContains(queued, "Destination") + self.assertContains(queued, "View import progress") run_directadmin_import(str(job.pk), "import_queued") job.refresh_from_db() self.assertEqual(job.state, "provisioning", job.problem) @@ -170,6 +179,20 @@ class DirectAdminWebImportTests(TestCase): self.assertFalse(archive_path(job.pk).exists()) self.assertFalse(HostingDatabase.objects.exists()) self.assertFalse(HostingMailbox.objects.exists()) + self.assertContains(self.client.get(self.url), "View import result") + self.assertContains(self.client.get(url), "Not requested") + + def test_status_poll_does_not_consume_the_submission_notification(self): + _, url = self.prepare() + self.assertEqual(self.submit(url).status_code, 302) + self.assertNotContains( + self.client.get(url, headers={"X-Coulobre-Status": "1"}), + "DirectAdmin import queued.", + ) + self.assertContains(self.client.get(url), "DirectAdmin import queued.") + self.assertNotContains( + self.client.get(url), "DirectAdmin import queued." + ) def test_rejects_nonempty_target_on_review_or_after_confirmation(self): account = HostingAccount.objects.create( diff --git a/src/coulobre/hosting/test_package_workflows.py b/src/coulobre/hosting/test_package_workflows.py index 4629e21..0a3244f 100644 --- a/src/coulobre/hosting/test_package_workflows.py +++ b/src/coulobre/hosting/test_package_workflows.py @@ -123,5 +123,10 @@ class PackageWorkflowTests(TestCase): ) response = self.client.get(reverse("panel:accounts")) self.assertContains(response, 'class="account-identity"', count=2) - self.assertNotContains(response, ">same.example") - self.assertContains(response, ">different.example") + self.assertContains(response, "Same as account name", count=1) + self.assertContains(response, "different.example", count=1) + self.assertContains(response, "Primary domain") + self.assertLess( + response.content.index(b">Primary domain<"), + response.content.index(b">Status<"), + ) diff --git a/src/coulobre/hosting/test_web_node_restore.py b/src/coulobre/hosting/test_web_node_restore.py index 9caebf6..b460019 100644 --- a/src/coulobre/hosting/test_web_node_restore.py +++ b/src/coulobre/hosting/test_web_node_restore.py @@ -11,6 +11,7 @@ from unittest.mock import patch from django.test import SimpleTestCase from coulobre.web_node import WebSite, main +from coulobre.web_node_apply import LEGACY_STARTER_PAGE, render_starter_page from coulobre.web_node_restore import copy_website, restore_website @@ -146,6 +147,59 @@ class DirectAdminWebRestoreTests(SimpleTestCase): self.assertEqual(list(self.public.iterdir()), [existing]) self.assertEqual(existing.read_bytes(), b"existing") + def test_only_stock_starter_page_can_be_replaced(self): + index = self.public / "index.html" + starter = render_starter_page(self.site.domain) + index.write_text(starter + "\n", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "empty document root"): + self.restore() + + index.unlink() + other_index = self.account / "other.html" + other_index.write_text(starter, encoding="utf-8") + index.symlink_to(other_index) + with self.assertRaisesRegex(ValueError, "empty document root"): + self.restore() + self.assertTrue(index.is_symlink()) + index.unlink() + + index.write_text(starter, encoding="utf-8") + self.assertEqual(self.restore()["files"], 6) + self.assertFalse(index.exists()) + self.assertEqual(other_index.read_text(encoding="utf-8"), starter) + self.assertEqual( + set(self.account.iterdir()), {self.public, other_index} + ) + + def test_legacy_starter_page_can_be_replaced(self): + (self.public / "index.html").write_text( + LEGACY_STARTER_PAGE, encoding="utf-8" + ) + self.assertEqual(self.restore()["files"], 6) + + def test_restore_keeps_both_versions_if_index_appears_during_publish(self): + index = self.public / "index.html" + starter = render_starter_page(self.site.domain) + index.write_text(starter, encoding="utf-8") + + def publish_with_concurrent_file(staged, public): + self.assertFalse(index.exists()) + index.write_bytes(b"new homepage") + raise ValueError("Restore requires an empty document root.") + + with ( + patch( + "coulobre.web_node_restore.publish_empty_webroot", + side_effect=publish_with_concurrent_file, + ), + self.assertRaisesRegex(ValueError, "private recovery directory"), + ): + self.restore() + + self.assertEqual(index.read_bytes(), b"new homepage") + (saved,) = self.account.glob(".directadmin-recovery-*/index.html") + self.assertEqual(saved.read_text(encoding="utf-8"), starter) + def test_atomic_publish_preserves_a_file_created_during_restore(self): existing = self.public / "new.txt" diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 0f24f3d..8594046 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -81,6 +81,19 @@ def starter_page_matches(page): return False +def is_starter_page(index): + try: + descriptor = os.open( + index, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK + ) + except OSError: + return False + with os.fdopen(descriptor, "rb") as page: + if not stat.S_ISREG(os.fstat(page.fileno()).st_mode): + return False + return starter_page_matches(page.read(starter_page_read_limit())) + + def starter_page_read_limit(): return ( max( diff --git a/src/coulobre/web_node_restore.py b/src/coulobre/web_node_restore.py index 1acb872..3475030 100644 --- a/src/coulobre/web_node_restore.py +++ b/src/coulobre/web_node_restore.py @@ -2,10 +2,23 @@ import errno import fcntl import os from pathlib import Path -from tempfile import TemporaryDirectory +from tempfile import TemporaryDirectory, mkdtemp from . import web_node_apply from .directadmin_website import copy_website +from .web_node_files import rename_entry + + +def starter_to_replace(public): + entries = os.listdir(public) + if not entries: + return None + index = public / "index.html" + if entries == [index.name] and web_node_apply.is_starter_page(index): + return index + raise ValueError( + "Restore requires an empty document root or the original starter page." + ) def check_website_empty(site): @@ -17,8 +30,7 @@ def check_website_empty(site): fcntl.flock(lock, fcntl.LOCK_SH) web_node_apply.check_reservation(site) public, _, _ = web_node_apply.site_storage(site) - if any(public.iterdir()): - raise ValueError("Restore requires an empty document root.") + starter_to_replace(public) def restore_website(site, backup, source_root): @@ -32,8 +44,7 @@ def restore_website(site, backup, source_root): paths = web_node_apply.SitePaths.for_site(site) uid, gid = web_node_apply.check_installation(site, paths) public = paths.account / "public" - if any(public.iterdir()): - raise ValueError("Restore requires an empty document root.") + starter_to_replace(public) with TemporaryDirectory( dir=paths.account, prefix=".directadmin-restore-" @@ -55,7 +66,7 @@ def restore_website(site, backup, source_root): on_copy=remember_private_entry, ) prepare_web_permissions(staged, uid, gid, private) - publish_empty_webroot(staged, public) + publish_directadmin_webroot(staged, public) return { **site.manifest(), @@ -66,6 +77,45 @@ def restore_website(site, backup, source_root): } +def publish_directadmin_webroot(staged, public): + index = starter_to_replace(public) + if index is None: + publish_empty_webroot(staged, public) + return + + recovery = Path( + mkdtemp(dir=public.parent, prefix=".directadmin-recovery-") + ) + saved = recovery / index.name + try: + os.replace(index, saved) + if not web_node_apply.is_starter_page(saved): + raise ValueError("The starter page changed during import.") + publish_empty_webroot(staged, public) + except BaseException: + if os.path.lexists(saved) and staged.exists(): + folder = os.open(public.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + rename_entry( + folder, + saved.relative_to(public.parent), + index.relative_to(public.parent), + ) + except (OSError, ValueError): + raise ValueError( + "The document root changed. The previous index was kept " + "in a private recovery directory on the web node." + ) from None + finally: + os.close(folder) + if not os.path.lexists(saved): + recovery.rmdir() + raise + else: + saved.unlink() + recovery.rmdir() + + def publish_empty_webroot(staged, public): try: # A rename can replace the live root while it is empty. diff --git a/src/coulobre/wordpress_node.py b/src/coulobre/wordpress_node.py index 28c7e98..27a36b6 100644 --- a/src/coulobre/wordpress_node.py +++ b/src/coulobre/wordpress_node.py @@ -140,24 +140,11 @@ def wordpress_version(cli, root): return version -def is_starter_page(index): - try: - descriptor = os.open( - index, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK - ) - except OSError: - return False - with os.fdopen(descriptor, "rb") as page: - if not stat.S_ISREG(os.fstat(page.fileno()).st_mode): - return False - contents = page.read(web.starter_page_read_limit()) - return web.starter_page_matches(contents) - - def check_install_target(public): entries = os.listdir(public) if entries and ( - entries != ["index.html"] or not is_starter_page(public / "index.html") + entries != ["index.html"] + or not web.is_starter_page(public / "index.html") ): raise ValueError( "Use an empty website or the original Coulobre starter page." @@ -174,7 +161,7 @@ def publish_wordpress(staged, public): saved = staged.parent / "previous-index" os.replace(index, saved) try: - if not is_starter_page(saved): + if not web.is_starter_page(saved): raise ValueError("The starter page changed during setup.") publish_empty_webroot(staged, public) except (OSError, ValueError, KeyboardInterrupt): diff --git a/tools/build_deb.py b/tools/build_deb.py index d7df790..a5c4ce7 100644 --- a/tools/build_deb.py +++ b/tools/build_deb.py @@ -81,6 +81,7 @@ def build_package(source, wheel, ref, output): units = root / "usr/lib/systemd/system" units.mkdir(parents=True) for name in ( + "coulobre-panel.service.d/import-storage.conf", "coulobre-directadmin-import-worker.service", "coulobre-directadmin-restore.socket", "coulobre-directadmin-restore@.service",