Apply selected WordPress updates with a recovery backup #239
No files matched your search
+25
-1
@@ -1390,7 +1390,7 @@ 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 WordPress installation and administrator setup
|
||||
## Enable WordPress management
|
||||
|
||||
Install the verified [WP-CLI Phar](https://make.wordpress.org/cli/handbook/guides/installing/#verifying-the-download-optional-but-recommended)
|
||||
as a root-owned regular file at `/usr/local/bin/wp` on the web node.
|
||||
@@ -1417,6 +1417,30 @@ configuration. If the panel reports an email failure, correct the
|
||||
site's outbound mail and use the WordPress password reset page. The
|
||||
setup workflow keeps passwords out of panel jobs, logs and email.
|
||||
|
||||
### Update WordPress, plugins and themes
|
||||
|
||||
Use WP-CLI 2.10 or later for fresh core update checks. Open the site's
|
||||
**WordPress** page, select **Check for updates**, and review the installed
|
||||
and available versions. Select **Back up and update** for one component
|
||||
at a time. The panel offers stable releases from WordPress.org. Use
|
||||
WordPress to manage extensions from other sources.
|
||||
|
||||
Updates require HTTPS, a single-site installation with its configuration
|
||||
in the site's document root, and a local MariaDB database managed by
|
||||
the hosting account. Enable local account backups and the website and
|
||||
database restore services. Coulobre creates a recovery archive with the
|
||||
selected document root and the entire database before applying the
|
||||
update, and checks that the advertised version is still available.
|
||||
Use a dedicated database for each WordPress site so that restoring its
|
||||
database does not replace tables for another application.
|
||||
|
||||
If an update fails after it starts, use the matching archive in
|
||||
**Backup & Restore** to recover the document root and database as needed.
|
||||
Customers can restore their own update backups. Update backups do not
|
||||
replace the customer's latest SFTP export. Managers can ask the server
|
||||
operator to restore a backup they requested. Schedule updates during a
|
||||
quiet period because WordPress may briefly display a maintenance page.
|
||||
|
||||
## Enable the website file manager
|
||||
|
||||
The installer enables the file manager, scheduled website jobs and local
|
||||
|
||||
@@ -80,6 +80,15 @@ def available_website_restore_targets(backup, current=None):
|
||||
}
|
||||
|
||||
|
||||
def require_no_wordpress_update(account):
|
||||
if account.wordpress_jobs.filter(
|
||||
action="update", finished_at__isnull=True
|
||||
).exists():
|
||||
raise ValidationError(
|
||||
"Wait for the current WordPress update to finish."
|
||||
)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def queue_website_restore(
|
||||
backup,
|
||||
@@ -93,6 +102,7 @@ def queue_website_restore(
|
||||
):
|
||||
account = lock_hosting_account(backup.account_id, customer_id=customer_id)
|
||||
require_active_services(account)
|
||||
require_no_wordpress_update(account)
|
||||
backup.refresh_from_db()
|
||||
if customer_id is not None and backup.export_customer_id != customer_id:
|
||||
raise ValidationError("This backup is no longer available.")
|
||||
@@ -130,6 +140,8 @@ def queue_component_restore(
|
||||
):
|
||||
account = lock_hosting_account(backup.account_id, customer_id=customer_id)
|
||||
require_active_services(account)
|
||||
if kind == RestoreKind.DATABASE:
|
||||
require_no_wordpress_update(account)
|
||||
backup.refresh_from_db()
|
||||
if customer_id is not None and backup.export_customer_id != customer_id:
|
||||
raise ValidationError("This backup is no longer available.")
|
||||
|
||||
@@ -70,7 +70,7 @@ class CustomerBackupView(UserPassesTestMixin, FormView):
|
||||
export_customer_id=self.account.customer_id,
|
||||
export_database_suffix="",
|
||||
)
|
||||
.select_related("expiration")
|
||||
.select_related("expiration", "wordpress_update")
|
||||
.order_by("-requested_at")[:30]
|
||||
)
|
||||
kinds = enabled_component_restores()
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 5.2.19 on 2026-12-02 00:18
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
("hosting", "0088_wordpress_operation"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="wordpressjob",
|
||||
name="backup",
|
||||
field=models.OneToOneField(
|
||||
null=True,
|
||||
on_delete=django.db.models.deletion.SET_NULL,
|
||||
related_name="wordpress_update",
|
||||
to="hosting.accountbackupjob",
|
||||
),
|
||||
),
|
||||
]
|
||||
@@ -1385,6 +1385,12 @@ class WordPressJob(ProvisioningJob):
|
||||
database = models.ForeignKey(
|
||||
HostingDatabase, on_delete=models.SET_NULL, null=True
|
||||
)
|
||||
backup = models.OneToOneField(
|
||||
"AccountBackupJob",
|
||||
on_delete=models.SET_NULL,
|
||||
null=True,
|
||||
related_name="wordpress_update",
|
||||
)
|
||||
details = models.JSONField(default=dict)
|
||||
report = models.JSONField(default=dict)
|
||||
|
||||
@@ -1427,7 +1433,10 @@ class AccountBackupJob(ProvisioningJob):
|
||||
|
||||
def can_restore_website(self, site):
|
||||
return self.archive_is_restorable and (
|
||||
self.manifest.get("website") == site.manifest()
|
||||
(
|
||||
self.manifest.get("include_website", True)
|
||||
and self.manifest.get("website") == site.manifest()
|
||||
)
|
||||
or site.manifest() in self.manifest.get("additional_websites", [])
|
||||
)
|
||||
|
||||
|
||||
@@ -192,8 +192,14 @@ def dispatch_web_activations():
|
||||
WordPressJob,
|
||||
run_wordpress_job,
|
||||
WEB_ACTIVATION_QUEUE,
|
||||
condition=Q(database__isnull=True)
|
||||
| Q(database__provisioning__finished_at__isnull=False),
|
||||
condition=(
|
||||
Q(database__isnull=True)
|
||||
| Q(database__provisioning__finished_at__isnull=False)
|
||||
)
|
||||
& (
|
||||
Q(backup__isnull=True)
|
||||
| Q(backup__finished_at__isnull=False)
|
||||
),
|
||||
)
|
||||
dispatch_provisioning_jobs(
|
||||
WebsiteRedirectPolicy,
|
||||
@@ -956,7 +962,10 @@ def create_backup_job_archive(job):
|
||||
job.backup_id,
|
||||
backup,
|
||||
remote_mail=job.remote_mail,
|
||||
publish_to_customer=job.export_customer_id is not None,
|
||||
publish_to_customer=(
|
||||
job.export_customer_id is not None
|
||||
and not hasattr(job, "wordpress_update")
|
||||
),
|
||||
database_suffix=job.export_database_suffix,
|
||||
)
|
||||
)
|
||||
@@ -1155,7 +1164,7 @@ def run_wordpress_job(job_id):
|
||||
if settings.WORDPRESS_MANAGEMENT and settings.LOCAL_WEB_ACTIVATION:
|
||||
run_provisioning_job(
|
||||
WordPressJob.objects.select_related(
|
||||
"account", "actor", "database"
|
||||
"account", "actor", "database", "backup", "backup__expiration"
|
||||
),
|
||||
job_id,
|
||||
run_wordpress_operation,
|
||||
|
||||
@@ -41,18 +41,69 @@
|
||||
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||
<button class="button secondary" name="action" value="inspect" type="submit">Detect WordPress</button>
|
||||
</form>
|
||||
{% if version %}
|
||||
<header class="section-heading">
|
||||
<div>
|
||||
<h2>WordPress.org updates</h2>
|
||||
<p class="heading-meta">Coulobre backs up this website and its database before applying each update.</p>
|
||||
</div>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||
<button class="button secondary" name="action" value="check-updates" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Check for updates</button>
|
||||
</form>
|
||||
</header>
|
||||
{% if inventory.updates %}
|
||||
{% if not updates_can_recover %}
|
||||
<p class="section-text">Ask your server operator to enable website and database recovery before updating.</p>
|
||||
{% elif not updates_has_database %}
|
||||
<p class="section-text">Panel updates require a local database managed by this hosting account.</p>
|
||||
{% endif %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Component</th><th scope="col">Installed</th><th scope="col">Available</th><th scope="col">Actions</th></tr></thead>
|
||||
<tbody>
|
||||
{% for update in inventory.updates %}
|
||||
<tr>
|
||||
<th scope="row">{% if update.kind == "core" %}WordPress core{% else %}{{ update.slug }} · {{ update.kind }}{% endif %}</th>
|
||||
<td>{{ update.installed }}</td>
|
||||
<td>{{ update.version }}</td>
|
||||
<td>
|
||||
{% if updates_can_recover and updates_has_database %}
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="site" value="{{ site.domain }}">
|
||||
<input type="hidden" name="selection" value="{{ update.kind }}:{{ update.slug }}:{{ update.installed }}:{{ update.version }}">
|
||||
<button class="button secondary" name="action" value="update" type="submit"{% if jobs and not jobs.0.finished_at %} disabled{% endif %}>Back up and update</button>
|
||||
</form>
|
||||
{% else %}—{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% elif inventory %}
|
||||
<p class="section-text">No available WordPress.org updates were reported.</p>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% if jobs %}
|
||||
<header class="section-heading"><h2>Operation history</h2></header>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Operation</th><th scope="col">Requested</th><th scope="col">Result</th></tr></thead>
|
||||
<tbody>
|
||||
{% for job in jobs %}
|
||||
<tr>
|
||||
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% else %}Detect{% endif %}</th>
|
||||
<th scope="row">{% if job.action == "add-admin" %}Add administrator{% elif job.action == "install" %}Install{% elif job.action == "check-updates" %}Check for updates{% elif job.action == "update" %}Update {{ job.details.update.slug }} to {{ job.details.update.version }}{% else %}Detect{% endif %}</th>
|
||||
<td>{{ job.requested_at }}</td>
|
||||
<td>
|
||||
{% if job.problem %}{{ job.problem }}
|
||||
{% else %}{{ job.state|capfirst }}{% endif %}
|
||||
{% if job.backup %}
|
||||
<br>Recovery backup requested {{ job.backup.requested_at }} · {{ job.backup.state|capfirst }}.
|
||||
{% if recovery_route %}<a href="{% url recovery_route account.pk %}">Backup & Restore</a>{% else %}Contact your server operator to restore it.{% endif %}
|
||||
{% endif %}
|
||||
{% if job.report.password_email == "accepted" %}<br>WordPress accepted the password setup email.
|
||||
{% elif job.report.password_email == "failed" %}<br>WordPress could not send the setup email. Check the website's mail settings and <a href="https://{{ site.domain }}/wp-login.php?action=lostpassword">request a password reset</a>.
|
||||
{% endif %}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<section class="surface" aria-labelledby="backup-history" data-live-status="customer-backups">
|
||||
<header class="section-heading"><h2 id="backup-history">Recent backups</h2></header>
|
||||
<ul class="workspace-list">
|
||||
{% for backup, kinds in backups %}<li>{{ backup.requested_at|date:"j M Y H:i" }} · {{ backup.state|capfirst }}
|
||||
{% for backup, kinds in backups %}<li>{{ backup.requested_at|date:"j M Y H:i" }} · {{ backup.state|capfirst }}{% if backup.wordpress_update %} · WordPress recovery backup{% endif %}
|
||||
{% for kind in kinds %}<a class="button secondary" href="{% url 'panel:customer_restore' account.pk backup.pk kind %}">Restore {{ kind }}</a>{% endfor %}
|
||||
</li>
|
||||
{% empty %}<li>No backups yet.</li>{% endfor %}
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
from pathlib import Path
|
||||
from subprocess import CompletedProcess
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest.mock import patch
|
||||
from unittest.mock import Mock, call, patch
|
||||
from uuid import uuid4
|
||||
from zipfile import ZipFile
|
||||
|
||||
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 MANIFEST_NAME, AccountBackup, manifest_text
|
||||
from coulobre.database_node import DatabaseSpec
|
||||
from coulobre.web_node import WebSite, parse_web_request
|
||||
from coulobre.web_node_apply import STARTER_PAGE
|
||||
from coulobre.wordpress import WordPressRequest
|
||||
from coulobre.wordpress_node import check_install_target, publish_wordpress
|
||||
from coulobre.wordpress_node_updates import (
|
||||
apply_update,
|
||||
verify_recovery_archive,
|
||||
)
|
||||
from coulobre.wordpress_updates import WordPressUpdate
|
||||
|
||||
from .models import (
|
||||
Customer,
|
||||
@@ -54,6 +63,63 @@ class InstallRequestTests(SimpleTestCase):
|
||||
email="owner@example.test",
|
||||
)
|
||||
|
||||
def test_independent_update_archive_cannot_restore_the_primary_site(self):
|
||||
primary = WebSite(7, "primary.test")
|
||||
site = WebSite(7, "wordpress.test", 9)
|
||||
database = DatabaseSpec(site.account_id, "wp")
|
||||
request = WordPressRequest(
|
||||
site,
|
||||
"update",
|
||||
database,
|
||||
update={
|
||||
"kind": "core",
|
||||
"slug": "wordpress",
|
||||
"installed": "7.0",
|
||||
"version": "7.1",
|
||||
},
|
||||
backup_id=str(uuid4()),
|
||||
)
|
||||
self.assertEqual(parse_web_request(request.manifest()), request)
|
||||
with self.assertRaisesRegex(ValueError, "Invalid WordPress update"):
|
||||
parse_web_request(
|
||||
request.manifest()
|
||||
| {
|
||||
"update": request.update | {"slug": "--force"},
|
||||
}
|
||||
)
|
||||
backup = AccountBackup(
|
||||
primary,
|
||||
(database,),
|
||||
additional_websites=(site,),
|
||||
include_website=False,
|
||||
)
|
||||
self.assertEqual(
|
||||
AccountBackup.from_manifest(backup.manifest()), backup
|
||||
)
|
||||
self.assertEqual(
|
||||
[resource for resource, _, _ in backup.components()],
|
||||
[site, database],
|
||||
)
|
||||
with TemporaryDirectory() as work:
|
||||
archive = Path(work) / "backup.zip"
|
||||
with (
|
||||
patch(
|
||||
"coulobre.wordpress_node_updates.backup_archive",
|
||||
return_value=archive,
|
||||
),
|
||||
patch("coulobre.wordpress_node_updates.check_root_file"),
|
||||
):
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "archive is unavailable"
|
||||
):
|
||||
verify_recovery_archive(request)
|
||||
with ZipFile(archive, "w") as bundle:
|
||||
bundle.writestr(MANIFEST_NAME, manifest_text(backup))
|
||||
for resource, manifest, component in backup.components():
|
||||
bundle.writestr(manifest, manifest_text(resource))
|
||||
bundle.writestr(component, b"example content")
|
||||
verify_recovery_archive(request)
|
||||
|
||||
def test_install_replaces_only_the_unmodified_starter_page(self):
|
||||
with TemporaryDirectory() as work:
|
||||
root = Path(work)
|
||||
@@ -191,3 +257,151 @@ class WordPressWorkflowTests(TestCase):
|
||||
enqueue.assert_called_once_with(
|
||||
args=[job.pk], queue="coulobre-web-activation", retry=False
|
||||
)
|
||||
|
||||
@override_settings(
|
||||
LOCAL_ACCOUNT_BACKUPS=True,
|
||||
LOCAL_WEBSITE_RESTORE=True,
|
||||
LOCAL_DATABASE_RESTORE=True,
|
||||
)
|
||||
@patch("coulobre.hosting.node_client.apply_on_local_node")
|
||||
@patch.object(run_wordpress_job, "apply_async")
|
||||
def test_update_waits_for_a_recovery_backup_of_the_selected_site_and_db(
|
||||
self, enqueue, apply
|
||||
):
|
||||
self.client.post(self.url, self.data)
|
||||
install = self.account.wordpress_jobs.get()
|
||||
provisioning = install.database.provisioning
|
||||
provisioning.finished_at = timezone.now()
|
||||
provisioning.save(update_fields=["finished_at"])
|
||||
apply.return_value = {"wp_version": "7.0"}
|
||||
run_wordpress_job.run(install.pk)
|
||||
self.client.post(self.url, self.data | {"action": "check-updates"})
|
||||
check = self.account.wordpress_jobs.latest("pk")
|
||||
selection = {
|
||||
"kind": "plugin",
|
||||
"slug": "akismet",
|
||||
"installed": "5.0",
|
||||
"version": "5.1",
|
||||
}
|
||||
apply.return_value = {
|
||||
"wp_version": "7.0",
|
||||
"database_name": install.database.spec.name,
|
||||
"updates": [selection],
|
||||
}
|
||||
run_wordpress_job.run(check.pk)
|
||||
self.assertContains(self.client.get(self.url), "Back up and update")
|
||||
request = self.data | {"action": "update"}
|
||||
response = self.client.post(
|
||||
self.url, request | {"selection": "plugin:akismet:5.0:5.2"}
|
||||
)
|
||||
self.assertContains(response, "select an available version again")
|
||||
self.assertFalse(self.account.backup_jobs.exists())
|
||||
|
||||
request["selection"] = "plugin:akismet:5.0:5.1"
|
||||
self.assertEqual(self.client.post(self.url, request).status_code, 302)
|
||||
update = self.account.wordpress_jobs.latest("pk")
|
||||
backup = update.backup
|
||||
self.assertEqual(update.database_id, install.database_id)
|
||||
self.assertEqual(backup.export_customer_id, self.customer.pk)
|
||||
self.assertEqual(backup.manifest["website"], update.site)
|
||||
self.assertEqual(
|
||||
backup.manifest["databases"], [install.database.spec.manifest()]
|
||||
)
|
||||
|
||||
dispatch_web_activations.run()
|
||||
enqueue.assert_not_called()
|
||||
backup.finished_at = timezone.now()
|
||||
backup.problem = "Backup worker could not archive the files."
|
||||
backup.save(update_fields=["finished_at", "problem"])
|
||||
dispatch_web_activations.run()
|
||||
enqueue.assert_called_once_with(
|
||||
args=[update.pk], queue="coulobre-web-activation", retry=False
|
||||
)
|
||||
apply.reset_mock()
|
||||
run_wordpress_job.run(update.pk)
|
||||
apply.assert_not_called()
|
||||
update.refresh_from_db()
|
||||
self.assertEqual(update.state, "failed")
|
||||
self.assertIn("recovery backup is unavailable", update.problem)
|
||||
|
||||
self.client.post(self.url, self.data | {"action": "check-updates"})
|
||||
run_wordpress_job.run(self.account.wordpress_jobs.latest("pk").pk)
|
||||
self.assertEqual(self.client.post(self.url, request).status_code, 302)
|
||||
second = self.account.wordpress_jobs.latest("pk")
|
||||
second.backup.finished_at = timezone.now()
|
||||
second.backup.save(update_fields=["finished_at"])
|
||||
apply.return_value = {"wp_version": "7.0"}
|
||||
run_wordpress_job.run(second.pk)
|
||||
second.refresh_from_db()
|
||||
self.assertEqual(second.state, "configured")
|
||||
self.assertEqual(apply.call_args.args[0].update, selection)
|
||||
self.assertEqual(
|
||||
apply.call_args.args[0].backup_id, str(second.backup.backup_id)
|
||||
)
|
||||
response = self.client.get(
|
||||
reverse("panel:customer_backups", args=[self.account.pk])
|
||||
)
|
||||
self.assertContains(response, "WordPress recovery backup")
|
||||
self.assertContains(response, "Restore database")
|
||||
|
||||
|
||||
class UpdateCommandTests(SimpleTestCase):
|
||||
@patch("coulobre.wordpress_node_updates.verify_recovery_archive")
|
||||
@patch("coulobre.wordpress_node_updates.database_name")
|
||||
@patch("coulobre.wordpress_node_updates.update_inventory")
|
||||
def test_selected_core_and_theme_commands_use_the_exact_version(
|
||||
self, inventory, database_name, verify_archive
|
||||
):
|
||||
site = WebSite(7, "wordpress.test")
|
||||
database = DatabaseSpec(site.account_id, "wp")
|
||||
database_name.return_value = database.name
|
||||
root = Path("/website")
|
||||
for kind, slug, commands in (
|
||||
(
|
||||
"core",
|
||||
"wordpress",
|
||||
[("core", "update", "--version=3.1"), ("core", "update-db")],
|
||||
),
|
||||
(
|
||||
"theme",
|
||||
"example",
|
||||
[
|
||||
("theme", "update", "example", "--version=3.1"),
|
||||
("theme", "get", "example", "--field=version"),
|
||||
],
|
||||
),
|
||||
):
|
||||
with self.subTest(kind=kind):
|
||||
update = WordPressUpdate(kind, slug, "3.0", "3.1")
|
||||
request = WordPressRequest(
|
||||
site,
|
||||
"update",
|
||||
database,
|
||||
update=update.manifest(),
|
||||
backup_id=str(uuid4()),
|
||||
)
|
||||
inventory.return_value = [update]
|
||||
cli = Mock()
|
||||
cli.require.return_value = CompletedProcess(
|
||||
args=(), returncode=0, stdout=b"3.1\n"
|
||||
)
|
||||
apply_update(request, cli, root, "3.0")
|
||||
self.assertEqual(verify_archive.call_args, call(request))
|
||||
self.assertEqual(
|
||||
inventory.call_args, call(cli, root, "3.0", kind)
|
||||
)
|
||||
self.assertEqual(
|
||||
[
|
||||
invocation.args[2:]
|
||||
for invocation in cli.require.call_args_list
|
||||
],
|
||||
commands,
|
||||
)
|
||||
|
||||
inventory.return_value = []
|
||||
cli.reset_mock()
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "selected update changed"
|
||||
):
|
||||
apply_update(request, cli, root, "3.0")
|
||||
cli.require.assert_not_called()
|
||||
@@ -1,3 +1,4 @@
|
||||
from datetime import timedelta
|
||||
from secrets import token_hex
|
||||
|
||||
from django.conf import settings
|
||||
@@ -5,12 +6,15 @@ from django.core.exceptions import PermissionDenied, ValidationError
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from coulobre.account_backup import AccountBackup
|
||||
from coulobre.web_node import WebSite
|
||||
from coulobre.wordpress import VERSION, WordPressRequest
|
||||
from coulobre.wordpress_updates import validate_update_inventory
|
||||
|
||||
from .access import customer_for_user, manages_account, reseller_for_user
|
||||
from .backup_restores import RestoreKind, require_no_wordpress_update
|
||||
from .installation_features import panel_feature_allowed
|
||||
from .models import WordPressJob
|
||||
from .models import ComponentRestoreJob, WebsiteRestoreJob, WordPressJob
|
||||
from .panel_roles import assigned_roles, scoped_user
|
||||
from .resource_requests import (
|
||||
create_database_request,
|
||||
@@ -18,6 +22,8 @@ from .resource_requests import (
|
||||
require_active_services,
|
||||
)
|
||||
|
||||
UPDATE_INVENTORY_AGE = timedelta(minutes=30)
|
||||
|
||||
PERMISSIONS = (
|
||||
"hosting.view_hostingaccount",
|
||||
"hosting.change_hostingaccount",
|
||||
@@ -55,6 +61,96 @@ def active_sites(account):
|
||||
return account_certificate_sites(account)
|
||||
|
||||
|
||||
def can_recover_updates():
|
||||
return (
|
||||
panel_feature_allowed("LOCAL_ACCOUNT_BACKUPS")
|
||||
and settings.LOCAL_WEBSITE_RESTORE
|
||||
and settings.LOCAL_DATABASE_RESTORE
|
||||
)
|
||||
|
||||
|
||||
def current_update_inventory(jobs):
|
||||
recent = (
|
||||
jobs.filter(action__in=("check-updates", "update"))
|
||||
.order_by("-pk")
|
||||
.first()
|
||||
)
|
||||
if (
|
||||
recent
|
||||
and recent.action == "check-updates"
|
||||
and recent.state == "configured"
|
||||
and recent.finished_at >= timezone.now() - UPDATE_INVENTORY_AGE
|
||||
):
|
||||
return recent.report
|
||||
return {}
|
||||
|
||||
|
||||
def update_database(account, name):
|
||||
return (
|
||||
next(
|
||||
(
|
||||
database
|
||||
for database in account.databases.filter(
|
||||
provisioning__finished_at__isnull=False,
|
||||
provisioning__problem="",
|
||||
)
|
||||
if database.spec.name == name
|
||||
),
|
||||
None,
|
||||
)
|
||||
if name
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def prepare_update_recovery(account, site, actor, jobs, selection):
|
||||
if not can_recover_updates():
|
||||
raise ValidationError(
|
||||
"Enable local website and database recovery first."
|
||||
)
|
||||
require_no_wordpress_update(account)
|
||||
if (
|
||||
WebsiteRestoreJob.objects.filter(
|
||||
backup__account=account, finished_at__isnull=True
|
||||
).exists()
|
||||
or ComponentRestoreJob.objects.filter(
|
||||
backup__account=account,
|
||||
kind=RestoreKind.DATABASE,
|
||||
finished_at__isnull=True,
|
||||
).exists()
|
||||
):
|
||||
raise ValidationError(
|
||||
"Wait for the current restore before updating WordPress."
|
||||
)
|
||||
inventory = current_update_inventory(jobs)
|
||||
if selection not in inventory.get("updates", ()):
|
||||
raise ValidationError(
|
||||
"Check for updates and select an available version again."
|
||||
)
|
||||
database = update_database(account, inventory.get("database_name"))
|
||||
if database is None:
|
||||
raise ValidationError(
|
||||
"Updates require a local database managed by this account."
|
||||
)
|
||||
if account.backup_jobs.filter(finished_at__isnull=True).exists():
|
||||
raise ValidationError(
|
||||
"Wait for the current backup before updating WordPress."
|
||||
)
|
||||
primary = WebSite(account.pk, account.primary_domain)
|
||||
manifest = AccountBackup(
|
||||
primary,
|
||||
(database.spec,),
|
||||
additional_websites=(site,) if site.site_id else (),
|
||||
include_website=site.site_id is None,
|
||||
).manifest()
|
||||
customer = customer_for_user(actor)
|
||||
backup = account.backup_jobs.create(
|
||||
manifest=manifest,
|
||||
export_customer_id=customer.pk if customer is not None else None,
|
||||
)
|
||||
return database, backup
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def queue_wordpress_job(account, site, actor, action, details):
|
||||
account = lock_hosting_account(account.pk, customer_id=None)
|
||||
@@ -67,7 +163,7 @@ def queue_wordpress_job(account, site, actor, action, details):
|
||||
jobs = account.wordpress_jobs.filter(site=site.manifest())
|
||||
if jobs.filter(finished_at__isnull=True).exists():
|
||||
raise ValidationError("Wait for the current WordPress operation.")
|
||||
database = None
|
||||
database = backup = None
|
||||
if action == "install":
|
||||
if not panel_feature_allowed("LOCAL_DATABASE_PROVISIONING"):
|
||||
raise ValidationError(
|
||||
@@ -93,9 +189,19 @@ def queue_wordpress_job(account, site, actor, action, details):
|
||||
database = create_database_request(
|
||||
account.pk, "wp_" + token_hex(4), auto_provision=True
|
||||
)
|
||||
elif action == "update":
|
||||
database, backup = prepare_update_recovery(
|
||||
account, site, actor, jobs, details.get("update")
|
||||
)
|
||||
request_details = details.copy()
|
||||
if backup is not None:
|
||||
request_details["backup_id"] = str(backup.backup_id)
|
||||
try:
|
||||
WordPressRequest(
|
||||
site, action, database.spec if database else None, **details
|
||||
site,
|
||||
action,
|
||||
database.spec if database else None,
|
||||
**request_details,
|
||||
)
|
||||
except ValueError as error:
|
||||
raise ValidationError(str(error)) from error
|
||||
@@ -107,6 +213,7 @@ def queue_wordpress_job(account, site, actor, action, details):
|
||||
action=action,
|
||||
details=details,
|
||||
database=database,
|
||||
backup=backup,
|
||||
)
|
||||
|
||||
|
||||
@@ -127,14 +234,28 @@ def run_wordpress_operation(job):
|
||||
if active_sites(account).get(site.domain) != site:
|
||||
raise ValueError("This website is no longer active.")
|
||||
database = job.database
|
||||
if job.action == "install" and (
|
||||
if job.action in ("install", "update") and (
|
||||
database is None
|
||||
or database.account_id != account.pk
|
||||
or database.provisioning.state != "configured"
|
||||
):
|
||||
raise ValueError("The WordPress database is not ready.")
|
||||
details = job.details.copy()
|
||||
if job.action == "update":
|
||||
backup = job.backup
|
||||
if (
|
||||
not can_recover_updates()
|
||||
or backup is None
|
||||
or backup.account_id != account.pk
|
||||
or not backup.archive_is_restorable
|
||||
):
|
||||
raise ValueError(
|
||||
"The recovery backup is unavailable. "
|
||||
"Try checking for updates again."
|
||||
)
|
||||
details["backup_id"] = str(backup.backup_id)
|
||||
spec = WordPressRequest(
|
||||
site, job.action, database.spec if database else None, **job.details
|
||||
site, job.action, database.spec if database else None, **details
|
||||
)
|
||||
reply = apply_on_local_node(
|
||||
spec,
|
||||
@@ -148,14 +269,15 @@ def run_wordpress_operation(job):
|
||||
if (
|
||||
not isinstance(version, str)
|
||||
or (version and not VERSION.fullmatch(version))
|
||||
or (job.action != "inspect" and not version)
|
||||
or (job.action not in ("inspect", "check-updates") and not version)
|
||||
or email not in ("", "accepted", "failed")
|
||||
):
|
||||
raise ValueError("The web node returned an invalid WordPress report.")
|
||||
return {
|
||||
"report": {
|
||||
"version": version,
|
||||
"password_email": email,
|
||||
"checked_at": timezone.now().isoformat(),
|
||||
}
|
||||
report = {
|
||||
"version": version,
|
||||
"password_email": email,
|
||||
"checked_at": timezone.now().isoformat(),
|
||||
}
|
||||
if job.action == "check-updates":
|
||||
report.update(validate_update_inventory(reply))
|
||||
return {"report": report}
|
||||
@@ -10,15 +10,19 @@ from django.views.decorators.cache import never_cache
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from coulobre.wordpress import LOGIN
|
||||
from coulobre.wordpress_updates import WordPressUpdate
|
||||
|
||||
from .access import TenantScopeMixin
|
||||
from .access import TenantScopeMixin, customer_for_user, is_tenant
|
||||
from .installation_features import panel_feature_allowed
|
||||
from .models import HostingAccount
|
||||
from .wordpress_management import (
|
||||
PERMISSIONS,
|
||||
active_sites,
|
||||
can_manage_wordpress,
|
||||
can_recover_updates,
|
||||
current_update_inventory,
|
||||
queue_wordpress_job,
|
||||
update_database,
|
||||
wordpress_available,
|
||||
)
|
||||
|
||||
@@ -36,6 +40,20 @@ class WordPressInstallForm(AdministratorForm):
|
||||
field_order = ("title", "username", "email", "confirmed")
|
||||
|
||||
|
||||
class WordPressUpdateForm(forms.Form):
|
||||
selection = forms.CharField(max_length=140)
|
||||
|
||||
def clean_selection(self):
|
||||
try:
|
||||
return WordPressUpdate(
|
||||
*self.cleaned_data["selection"].split(":")
|
||||
).manifest()
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError(
|
||||
"Choose an available WordPress update."
|
||||
) from None
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class AccountWordPressView(
|
||||
TenantScopeMixin, PermissionRequiredMixin, SingleObjectMixin, View
|
||||
@@ -76,6 +94,8 @@ class AccountWordPressView(
|
||||
action = request.POST.get("action")
|
||||
forms_for_action = {
|
||||
"inspect": forms.Form,
|
||||
"check-updates": forms.Form,
|
||||
"update": WordPressUpdateForm,
|
||||
"install": WordPressInstallForm,
|
||||
"add-admin": AdministratorForm,
|
||||
}
|
||||
@@ -88,6 +108,8 @@ class AccountWordPressView(
|
||||
for name, value in form.cleaned_data.items()
|
||||
if name != "confirmed"
|
||||
}
|
||||
if action == "update":
|
||||
details = {"update": details["selection"]}
|
||||
try:
|
||||
queue_wordpress_job(
|
||||
self.account, self.site, request.user, action, details
|
||||
@@ -104,16 +126,30 @@ class AccountWordPressView(
|
||||
def page(self, *, action=None, form=None):
|
||||
jobs = ()
|
||||
known_version = ""
|
||||
inventory = {}
|
||||
if self.site:
|
||||
history = self.account.wordpress_jobs.filter(
|
||||
site=self.site.manifest()
|
||||
).order_by("-pk")
|
||||
jobs = list(history[:10])
|
||||
jobs = list(history.select_related("backup")[:10])
|
||||
inventory = current_update_inventory(history)
|
||||
last = history.filter(
|
||||
finished_at__isnull=False, problem=""
|
||||
).first()
|
||||
if last:
|
||||
known_version = last.report.get("version", "")
|
||||
user = self.request.user
|
||||
recovery_route = ""
|
||||
if customer_for_user(user) is not None:
|
||||
recovery_route = "panel:customer_backups"
|
||||
elif not is_tenant(user) and user.has_perms(
|
||||
(
|
||||
"hosting.view_webprovisioningplan",
|
||||
"hosting.view_hostingdatabase",
|
||||
"hosting.add_accountbackupjob",
|
||||
)
|
||||
):
|
||||
recovery_route = "panel:account_backup_archives"
|
||||
return render(
|
||||
self.request,
|
||||
"hosting/account_wordpress.html",
|
||||
@@ -123,9 +159,16 @@ class AccountWordPressView(
|
||||
"site": self.site,
|
||||
"version": known_version,
|
||||
"jobs": jobs,
|
||||
"operation_errors": form.non_field_errors()
|
||||
if action == "inspect"
|
||||
"operation_errors": form.errors
|
||||
if action in ("inspect", "check-updates", "update")
|
||||
else (),
|
||||
"inventory": inventory,
|
||||
"updates_can_recover": can_recover_updates(),
|
||||
"updates_has_database": update_database(
|
||||
self.account, inventory.get("database_name")
|
||||
)
|
||||
is not None,
|
||||
"recovery_route": recovery_route,
|
||||
"install_form": form
|
||||
if action == "install"
|
||||
else WordPressInstallForm(
|
||||
|
||||
Reference in new issue
Block a user