Prepare Coulobre 0.10.1 with panel workflow improvements and web updates #135
No files matched your search
@@ -856,6 +856,12 @@ class Installer:
|
||||
HEALTH_TIMER,
|
||||
):
|
||||
install_unit(unit)
|
||||
if not REMOTE_MODES.intersection(
|
||||
(self.plan.dns.mode, self.plan.mail.mode)
|
||||
):
|
||||
install_unit("coulobre-update.socket")
|
||||
install_unit("coulobre-update@.service")
|
||||
workers.append("coulobre-update.socket")
|
||||
systemctl("daemon-reload")
|
||||
systemctl(
|
||||
"enable", "--now", *PANEL_UNITS, *workers, "apache2.service"
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Coulobre single-server release updater socket
|
||||
|
||||
[Socket]
|
||||
ListenStream=/run/coulobre-update.sock
|
||||
SocketUser=coulobre-panel
|
||||
SocketGroup=root
|
||||
SocketMode=0600
|
||||
Accept=yes
|
||||
MaxConnections=3
|
||||
RemoveOnStop=true
|
||||
|
||||
[Install]
|
||||
WantedBy=sockets.target
|
||||
@@ -0,0 +1,22 @@
|
||||
[Unit]
|
||||
Description=Coulobre single-server release update
|
||||
After=mariadb.service network-online.target
|
||||
CollectMode=inactive-or-failed
|
||||
|
||||
[Service]
|
||||
Type=exec
|
||||
User=root
|
||||
WorkingDirectory=/opt/coulobre
|
||||
EnvironmentFile=/etc/coulobre/panel.env
|
||||
StateDirectory=coulobre-update
|
||||
StateDirectoryMode=0755
|
||||
UMask=0077
|
||||
ExecStart=/opt/coulobre/bin/coulobre-update
|
||||
StandardInput=socket
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
RuntimeMaxSec=60min
|
||||
NoNewPrivileges=true
|
||||
ProtectHome=true
|
||||
ProtectSystem=strict
|
||||
ReadWritePaths=/opt/coulobre
|
||||
@@ -30,6 +30,7 @@ coulobre-mail-node = "coulobre.mail_node:main"
|
||||
coulobre-node-setup = "coulobre.node_setup:main"
|
||||
coulobre-service-credentials = "coulobre.service_credentials:main"
|
||||
coulobre-service-health = "coulobre.service_health:main"
|
||||
coulobre-update = "coulobre.local_update:main"
|
||||
coulobre-web-node = "coulobre.web_node:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
{% endif %}
|
||||
{% if group_customer_navigation %}</details>{% endif %}
|
||||
{% if is_operator and perms.hosting.view_servicehealth %}
|
||||
<details class="sidebar-group"{% if panel_section == 'plans' or panel_section == 'service_health' or panel_section == 'installation' or panel_section == 'dns_defaults' %} open{% endif %}>
|
||||
<details class="sidebar-group"{% if panel_section == 'plans' or panel_section == 'service_health' or panel_section == 'installation' or panel_section == 'dns_defaults' or panel_section == 'updates' %} open{% endif %}>
|
||||
<summary>Server and services</summary>
|
||||
{% endif %}
|
||||
{% if is_reseller or is_operator and perms.hosting.view_webprovisioningplan %}
|
||||
@@ -72,6 +72,10 @@
|
||||
About Coulobre
|
||||
</a>
|
||||
{% if request.user.is_superuser %}
|
||||
<a href="{% url 'panel:updates' %}"{% if current == 'updates' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
|
||||
Updates
|
||||
</a>
|
||||
<a href="{% url 'panel:dns_defaults' %}"{% if current == 'dns_defaults' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-plans" aria-hidden="true"></span>
|
||||
DNS zone template
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Updates · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<header class="page-heading">
|
||||
<div><h1>Updates</h1><p class="heading-meta">Installed version {{ installed_version|default:"unknown" }}</p></div>
|
||||
<a class="button secondary" href="{% url 'panel:updates' %}">Refresh status</a>
|
||||
</header>
|
||||
{% for message in messages %}<p class="notice" role="status">{{ message }}</p>{% endfor %}
|
||||
{% if form.errors %}<div class="notice">{{ form.errors }}</div>{% endif %}
|
||||
{% if update_status %}
|
||||
<section class="surface" aria-labelledby="update-status">
|
||||
<header class="section-heading"><h2 id="update-status">Latest update</h2><span>{{ update_status.target_version }}</span></header>
|
||||
<p class="section-text">{{ update_status.message }}</p>
|
||||
<p class="section-text muted">Requested by {{ update_status.actor }} · {{ update_status.updated_at }}</p>
|
||||
{% if update_status.state == "recovery_required" %}
|
||||
<p class="section-text">Review the updater journal and recovery files in <code>/var/lib/coulobre-update/</code> before starting another upgrade.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if not updater_enabled %}
|
||||
<section class="surface"><p class="empty">Enable the local updater socket on an installer-managed single server to use web updates.</p></section>
|
||||
{% elif catalog_problem %}
|
||||
<section class="surface"><p class="empty">{{ catalog_problem }}</p></section>
|
||||
{% else %}
|
||||
<section class="surface" aria-labelledby="available-updates">
|
||||
<header class="section-heading"><h2 id="available-updates">Compatible releases</h2></header>
|
||||
{% for release in releases %}
|
||||
<details class="section-text">
|
||||
<summary>{{ release.version }}{% if release.prerelease %} · Prerelease{% endif %}</summary>
|
||||
{{ release.notes|linebreaks }}
|
||||
{% if may_apply and update_status.state != "running" and update_status.state != "recovery_required" %}
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="version" value="{{ release.version }}">
|
||||
<input type="hidden" name="sha256" value="{{ release.sha256 }}">
|
||||
<label><input type="checkbox" name="confirm" required> I reviewed this release and want to update this server.</label>
|
||||
<p class="heading-meta">The panel goes offline while the updater creates a recovery backup and installs the release.</p>
|
||||
<button class="button primary" type="submit">Install {{ release.version }}</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</details>
|
||||
{% empty %}
|
||||
<p class="empty">No compatible web updates are published.</p>
|
||||
{% endfor %}
|
||||
{% if releases and not may_apply %}<p class="section-text">Sign in with two-factor authentication to install an update.</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,98 @@
|
||||
import json
|
||||
import socket
|
||||
from importlib.metadata import PackageNotFoundError, version
|
||||
|
||||
from django import forms
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth.mixins import UserPassesTestMixin
|
||||
from django.core.cache import cache
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.decorators import method_decorator
|
||||
from django.views.decorators.cache import never_cache
|
||||
from django.views.generic import FormView
|
||||
|
||||
from coulobre.local_update import SOCKET, display_status
|
||||
from coulobre.release_updates import (
|
||||
UpdateError,
|
||||
available_releases,
|
||||
version_key,
|
||||
)
|
||||
|
||||
|
||||
class UpdateForm(forms.Form):
|
||||
version = forms.CharField(max_length=32, widget=forms.HiddenInput)
|
||||
sha256 = forms.RegexField(
|
||||
regex=r"\A[0-9a-f]{64}\Z", widget=forms.HiddenInput
|
||||
)
|
||||
confirm = forms.BooleanField(
|
||||
label="I reviewed this release and want to update this server."
|
||||
)
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class UpdateView(UserPassesTestMixin, FormView):
|
||||
form_class = UpdateForm
|
||||
template_name = "hosting/updates.html"
|
||||
success_url = reverse_lazy("panel:updates")
|
||||
|
||||
def test_func(self):
|
||||
return self.request.user.is_superuser
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context["update_status"] = display_status()
|
||||
context["updater_enabled"] = SOCKET.is_socket()
|
||||
context["may_apply"] = self.request.user.is_verified()
|
||||
try:
|
||||
installed = version("coulobre-panel")
|
||||
except PackageNotFoundError:
|
||||
context["catalog_problem"] = (
|
||||
"The installed release version is unavailable."
|
||||
)
|
||||
return context
|
||||
context["installed_version"] = installed
|
||||
if context["updater_enabled"]:
|
||||
try:
|
||||
context["releases"] = cache.get_or_set(
|
||||
f"coulobre-updates:{installed}",
|
||||
lambda: available_releases(installed),
|
||||
timeout=300,
|
||||
)
|
||||
except UpdateError as error:
|
||||
context["catalog_problem"] = str(error)
|
||||
return context
|
||||
|
||||
def form_valid(self, form):
|
||||
if not self.request.user.is_verified():
|
||||
raise PermissionDenied
|
||||
payload = {
|
||||
"version": form.cleaned_data["version"],
|
||||
"sha256": form.cleaned_data["sha256"],
|
||||
"actor": self.request.user.get_username(),
|
||||
}
|
||||
try:
|
||||
version_key(payload["version"])
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(6)
|
||||
peer.connect(str(SOCKET))
|
||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||
with peer.makefile("rb") as reply:
|
||||
result = json.loads(reply.readline(4096))
|
||||
if not result.get("accepted"):
|
||||
raise UpdateError(result["message"])
|
||||
except (OSError, ValueError):
|
||||
form.add_error(
|
||||
None,
|
||||
"The local updater could not be reached. "
|
||||
"Check its socket and service logs.",
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
except UpdateError as error:
|
||||
form.add_error(None, str(error))
|
||||
return self.form_invalid(form)
|
||||
messages.success(
|
||||
self.request,
|
||||
"Update accepted. Check this page again after the panel restarts.",
|
||||
)
|
||||
return super().form_valid(form)
|
||||
@@ -47,6 +47,7 @@ from .sign_in import (
|
||||
PanelLoginView,
|
||||
VerifyFactorView,
|
||||
)
|
||||
from .update_views import UpdateView
|
||||
from .website_file_views import WebsiteFilesView
|
||||
from .website_job_views import WebsiteJobEditor, WebsiteJobList
|
||||
from .website_usage_views import WebsiteUsageView
|
||||
@@ -55,6 +56,7 @@ app_name = "panel"
|
||||
|
||||
urlpatterns = [
|
||||
path("panel-theme.css", themes.stylesheet, name="theme_stylesheet"),
|
||||
path("updates/", UpdateView.as_view(), name="updates"),
|
||||
path("dns-template/", DnsDefaultsView.as_view(), name="dns_defaults"),
|
||||
path(
|
||||
"accounts/<int:pk>/setup/",
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from datetime import UTC, datetime
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
from pwd import getpwnam
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .release_updates import UpdateError, download_wheel, selected_release
|
||||
|
||||
SOCKET = Path("/run/coulobre-update.sock")
|
||||
STATE = Path("/var/lib/coulobre-update")
|
||||
STATUS = STATE / "status.json"
|
||||
LOCK = STATE / "update.lock"
|
||||
PANEL = "coulobre-panel.service"
|
||||
BEAT = "coulobre-beat.service"
|
||||
WORKER = "coulobre-worker.service"
|
||||
MANAGED_UNITS = frozenset(
|
||||
{
|
||||
PANEL,
|
||||
BEAT,
|
||||
WORKER,
|
||||
"coulobre-health.timer",
|
||||
"coulobre-account-backup.socket",
|
||||
"coulobre-account-offsite.socket",
|
||||
"coulobre-account-restore.socket",
|
||||
"coulobre-backup-worker.service",
|
||||
"coulobre-database-apply.socket",
|
||||
"coulobre-database-provisioner.service",
|
||||
"coulobre-dns-apply.socket",
|
||||
"coulobre-dns-publisher.service",
|
||||
"coulobre-https-apply.socket",
|
||||
"coulobre-https-provisioner.service",
|
||||
"coulobre-mail-apply.socket",
|
||||
"coulobre-mail-archive-backup.socket",
|
||||
"coulobre-mail-archive-restore.socket",
|
||||
"coulobre-mail-credentials.socket",
|
||||
"coulobre-mailbox-provisioner.service",
|
||||
"coulobre-offsite-worker.service",
|
||||
"coulobre-provisioner.service",
|
||||
"coulobre-service-credentials.socket",
|
||||
"coulobre-sftp-apply.socket",
|
||||
"coulobre-sftp-provisioner.service",
|
||||
"coulobre-web-apply.socket",
|
||||
"coulobre-website-files.socket",
|
||||
"coulobre-website-job-worker.service",
|
||||
"coulobre-website-jobs.socket",
|
||||
"coulobre-website-usage.socket",
|
||||
}
|
||||
)
|
||||
VENV = Path("/opt/coulobre")
|
||||
PYTHON = VENV / "bin/python"
|
||||
CONFIG = Path("/etc/coulobre/panel.env")
|
||||
INSTALLATION = Path("/var/lib/coulobre-installer/installation.json")
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
REMOTE_RELAY = (
|
||||
"coulobre-dns-apply@.service.d/remote.conf",
|
||||
"coulobre-mail-apply@.service.d/remote.conf",
|
||||
)
|
||||
ROOT_COMMAND_ENV = {
|
||||
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
|
||||
"LC_ALL": "C.UTF-8",
|
||||
}
|
||||
|
||||
|
||||
def read_status():
|
||||
try:
|
||||
payload = json.loads(STATUS.read_text())
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def publish_status(status, state, message):
|
||||
status.update(
|
||||
state=state, message=message, updated_at=datetime.now(UTC).isoformat()
|
||||
)
|
||||
staged = STATUS.with_suffix(".new")
|
||||
with staged.open("w", encoding="utf-8") as stream:
|
||||
json.dump(status, stream)
|
||||
stream.write("\n")
|
||||
os.fchmod(stream.fileno(), 0o644)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
staged.replace(STATUS)
|
||||
directory = os.open(STATUS.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory)
|
||||
finally:
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def display_status():
|
||||
status = read_status()
|
||||
if status.get("state") == "running":
|
||||
try:
|
||||
with LOCK.open("rb") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
status = read_status()
|
||||
if status.get("state") == "running":
|
||||
status.update(
|
||||
state="recovery_required",
|
||||
message=(
|
||||
"The update was interrupted. "
|
||||
"Review the recovery files."
|
||||
),
|
||||
)
|
||||
except OSError:
|
||||
pass # The worker holds the lock, or the updater is unavailable.
|
||||
return status
|
||||
|
||||
|
||||
def root_controlled(path):
|
||||
info = path.lstat()
|
||||
return (
|
||||
info.st_uid == 0
|
||||
and not info.st_mode & 0o022
|
||||
and not stat.S_ISLNK(info.st_mode)
|
||||
)
|
||||
|
||||
|
||||
def check_installation():
|
||||
try:
|
||||
if not all(
|
||||
root_controlled(path) for path in (VENV, CONFIG, INSTALLATION)
|
||||
):
|
||||
raise ValueError
|
||||
installation = json.loads(INSTALLATION.read_text())
|
||||
plan = installation["plan"]
|
||||
if installation.get("complete") is not True or not all(
|
||||
plan[role]["mode"] in {"local", "off"} for role in ("dns", "mail")
|
||||
):
|
||||
raise ValueError
|
||||
if (
|
||||
any((SYSTEMD / relay).exists() for relay in REMOTE_RELAY)
|
||||
or Path("/etc/coulobre-remote").exists()
|
||||
):
|
||||
raise ValueError
|
||||
if (
|
||||
os.environ.get("COULOBRE_DB_NAME") != "coulobre_panel"
|
||||
or os.environ.get("COULOBRE_DB_HOST") != "/run/mysqld/mysqld.sock"
|
||||
):
|
||||
raise ValueError
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise UpdateError(
|
||||
"Web updates require a complete single-server installation "
|
||||
"with the installer-managed MariaDB database."
|
||||
) from error
|
||||
return plan["hostname"]
|
||||
|
||||
|
||||
def run(*args, log, timeout=900, stdout=None, umask=-1):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
check=True,
|
||||
timeout=timeout,
|
||||
env=ROOT_COMMAND_ENV,
|
||||
stdout=stdout if stdout is not None else subprocess.PIPE,
|
||||
stderr=log,
|
||||
stdin=subprocess.DEVNULL,
|
||||
umask=umask,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise UpdateError(
|
||||
f"{Path(args[0]).name} failed. Check the private update log."
|
||||
) from error
|
||||
return (result.stdout or b"").decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def active_units(log):
|
||||
listing = run(
|
||||
"/usr/bin/systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"--full",
|
||||
"coulobre-*",
|
||||
log=log,
|
||||
)
|
||||
return [
|
||||
unit
|
||||
for line in listing.splitlines()
|
||||
if line.strip()
|
||||
if (unit := line.split()[0]) in MANAGED_UNITS
|
||||
]
|
||||
|
||||
|
||||
def systemctl(action, units, log):
|
||||
if units:
|
||||
run("/usr/bin/systemctl", action, *units, log=log)
|
||||
|
||||
|
||||
def manage(*args, log):
|
||||
run(
|
||||
"/usr/bin/systemd-run",
|
||||
"--wait",
|
||||
"--pipe",
|
||||
"--collect",
|
||||
"--quiet",
|
||||
"--uid=coulobre-panel",
|
||||
"--property=EnvironmentFile=/etc/coulobre/panel.env",
|
||||
PYTHON,
|
||||
"-m",
|
||||
"django",
|
||||
*args,
|
||||
log=log,
|
||||
)
|
||||
|
||||
|
||||
def verify_panel(hostname, release, log):
|
||||
installed = run(
|
||||
PYTHON,
|
||||
"-c",
|
||||
"from importlib.metadata import version; "
|
||||
"print(version('coulobre-panel'))",
|
||||
log=log,
|
||||
).strip()
|
||||
if installed != release.version:
|
||||
raise UpdateError(
|
||||
"The installed version differs from the selected release."
|
||||
)
|
||||
request = (
|
||||
f"GET /sign-in/ HTTP/1.0\r\nHost: {hostname}\r\n"
|
||||
"X-Forwarded-Proto: https\r\n\r\n"
|
||||
)
|
||||
for _ in range(20):
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(2)
|
||||
peer.connect("/run/coulobre-panel/panel.sock")
|
||||
peer.sendall(request.encode("ascii"))
|
||||
with peer.makefile("rb") as reply:
|
||||
if reply.readline(256).split()[1:2] == [b"200"]:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise UpdateError(
|
||||
"The upgraded panel did not respond to the sign-in check."
|
||||
)
|
||||
|
||||
|
||||
def back_up(backup, log):
|
||||
shutil.copytree(VENV, backup / "venv", symlinks=True)
|
||||
shutil.copytree(CONFIG.parent, backup / "config", symlinks=True)
|
||||
with (backup / "panel.sql").open("xb") as dump:
|
||||
run(
|
||||
"/usr/bin/mariadb-dump",
|
||||
"--protocol=socket",
|
||||
"--user=root",
|
||||
"--socket=/run/mysqld/mysqld.sock",
|
||||
"--single-transaction",
|
||||
"--add-drop-database",
|
||||
"--databases",
|
||||
"coulobre_panel",
|
||||
stdout=dump,
|
||||
log=log,
|
||||
)
|
||||
if (backup / "panel.sql").stat().st_size == 0:
|
||||
raise UpdateError("The database recovery dump is empty.")
|
||||
|
||||
|
||||
def apply_update(status, request, hostname):
|
||||
backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ")
|
||||
backup.mkdir(mode=0o700)
|
||||
status["recovery"] = backup.name
|
||||
changed = False
|
||||
stopped = []
|
||||
with (
|
||||
(backup / "update.log").open("xb") as log,
|
||||
TemporaryDirectory(dir=STATE) as download,
|
||||
):
|
||||
try:
|
||||
release = selected_release(
|
||||
request["version"],
|
||||
status["installed_version"],
|
||||
request["sha256"],
|
||||
)
|
||||
publish_status(status, "running", "Verifying the release package.")
|
||||
wheel = download_wheel(release, download)
|
||||
active = active_units(log)
|
||||
if not {PANEL, BEAT, WORKER} <= set(active):
|
||||
raise UpdateError(
|
||||
"Start the panel, scheduler and worker before updating."
|
||||
)
|
||||
publish_status(
|
||||
status, "running", "Stopping the panel and its workers."
|
||||
)
|
||||
sockets = [
|
||||
unit for unit in active if unit.endswith((".socket", ".timer"))
|
||||
]
|
||||
services = [
|
||||
unit
|
||||
for unit in active
|
||||
if unit not in {PANEL, BEAT} and unit.endswith(".service")
|
||||
]
|
||||
stopped = active
|
||||
systemctl("stop", [PANEL, BEAT, *sockets], log)
|
||||
if "coulobre-health.timer" in active:
|
||||
systemctl("stop", ["coulobre-health.service"], log)
|
||||
systemctl("stop", services, log)
|
||||
if "Result=timeout" in run(
|
||||
"/usr/bin/systemctl",
|
||||
"show",
|
||||
"-p",
|
||||
"Result",
|
||||
*services,
|
||||
log=log,
|
||||
):
|
||||
raise UpdateError(
|
||||
"A worker did not shut down cleanly. "
|
||||
"Finish its jobs before retrying."
|
||||
)
|
||||
pending = run(
|
||||
"/usr/bin/systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating",
|
||||
"--plain",
|
||||
"--no-legend",
|
||||
"coulobre-*@*.service",
|
||||
log=log,
|
||||
)
|
||||
if any(
|
||||
not line.startswith("coulobre-update@")
|
||||
for line in pending.splitlines()
|
||||
if line.strip()
|
||||
):
|
||||
raise UpdateError(
|
||||
"A provisioning service is still running. "
|
||||
"Retry after it finishes."
|
||||
)
|
||||
(backup / "units.json").write_text(json.dumps(active))
|
||||
publish_status(status, "running", "Creating the recovery backup.")
|
||||
back_up(backup, log)
|
||||
publish_status(
|
||||
status, "running", "Installing the verified release."
|
||||
)
|
||||
changed = True
|
||||
run(
|
||||
PYTHON,
|
||||
"-m",
|
||||
"pip",
|
||||
"--isolated",
|
||||
"install",
|
||||
"--no-index",
|
||||
"--no-deps",
|
||||
wheel,
|
||||
log=log,
|
||||
umask=0o022,
|
||||
)
|
||||
run(PYTHON, "-m", "pip", "check", log=log)
|
||||
publish_status(
|
||||
status,
|
||||
"running",
|
||||
"Applying migrations and collecting static files.",
|
||||
)
|
||||
manage("check", log=log)
|
||||
manage("migrate", "--noinput", log=log)
|
||||
manage("collectstatic", "--noinput", log=log)
|
||||
publish_status(
|
||||
status, "running", "Starting services and verifying the panel."
|
||||
)
|
||||
systemctl("start", stopped, log)
|
||||
if not set(active) <= set(active_units(log)):
|
||||
raise UpdateError("Some panel services did not restart.")
|
||||
verify_panel(hostname, release, log)
|
||||
status["installed_version"] = release.version
|
||||
publish_status(
|
||||
status,
|
||||
"succeeded",
|
||||
"The updated panel responded and its services restarted.",
|
||||
)
|
||||
except (OSError, UpdateError) as error:
|
||||
if not changed:
|
||||
try:
|
||||
systemctl("start", stopped, log)
|
||||
except UpdateError:
|
||||
changed = True
|
||||
message = (
|
||||
str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "An update operation failed. Check the private log."
|
||||
)
|
||||
publish_status(
|
||||
status, "recovery_required" if changed else "failed", message
|
||||
)
|
||||
|
||||
|
||||
def read_request(peer):
|
||||
peer.settimeout(4)
|
||||
caller = peer.getsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
|
||||
)
|
||||
_, uid, _ = struct.unpack("3i", caller)
|
||||
if uid != getpwnam("coulobre-panel").pw_uid:
|
||||
raise UpdateError("Only the Coulobre panel can request updates.")
|
||||
with peer.makefile("rb") as stream:
|
||||
request = json.loads(stream.readline(2048))
|
||||
if not isinstance(request, dict) or set(request) != {
|
||||
"version",
|
||||
"sha256",
|
||||
"actor",
|
||||
}:
|
||||
raise UpdateError("The update request is invalid.")
|
||||
if not all(
|
||||
isinstance(value, str)
|
||||
and value
|
||||
and len(value) <= 160
|
||||
and value.isprintable()
|
||||
for value in request.values()
|
||||
):
|
||||
raise UpdateError("The update request is invalid.")
|
||||
return request
|
||||
|
||||
|
||||
def reply(peer, **payload):
|
||||
peer.sendall(json.dumps(payload).encode() + b"\n")
|
||||
|
||||
|
||||
def handle_request(peer):
|
||||
request = read_request(peer)
|
||||
with LOCK.open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError as error:
|
||||
raise UpdateError("An update is already running.") from error
|
||||
os.fchmod(lock.fileno(), 0o644)
|
||||
previous = read_status()
|
||||
if previous.get("state") == "running":
|
||||
publish_status(
|
||||
previous,
|
||||
"recovery_required",
|
||||
"The previous update was interrupted. "
|
||||
"Review the recovery files.",
|
||||
)
|
||||
if previous.get("state") == "recovery_required":
|
||||
raise UpdateError(
|
||||
"Resolve the previous update before starting another one."
|
||||
)
|
||||
installed = version("coulobre-panel")
|
||||
status = {
|
||||
"installed_version": installed,
|
||||
"target_version": request["version"],
|
||||
"actor": request["actor"],
|
||||
}
|
||||
try:
|
||||
hostname = check_installation()
|
||||
except UpdateError as error:
|
||||
publish_status(status, "failed", str(error))
|
||||
raise
|
||||
publish_status(status, "running", "Checking release compatibility.")
|
||||
reply(peer, accepted=True)
|
||||
peer.close()
|
||||
apply_update(status, request, hostname)
|
||||
|
||||
|
||||
def main():
|
||||
with socket.socket(fileno=0) as peer:
|
||||
try:
|
||||
handle_request(peer)
|
||||
except (OSError, ValueError, UpdateError) as error:
|
||||
message = (
|
||||
str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "Could not accept the update request."
|
||||
)
|
||||
with suppress(OSError):
|
||||
reply(peer, accepted=False, message=message)
|
||||
@@ -0,0 +1,187 @@
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
ORIGIN = "https://code.hosting.hippogrief.nl"
|
||||
REPOSITORY = "hippogrief/coulobre"
|
||||
MANIFEST = "web-update.json"
|
||||
VERSION = re.compile(
|
||||
r"(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})(?:rc([1-9][0-9]{0,5}))?"
|
||||
)
|
||||
SHA256 = re.compile(r"[0-9a-f]{64}")
|
||||
MAX_WHEEL = 32 * 1024 * 1024
|
||||
|
||||
|
||||
class UpdateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def version_key(value):
|
||||
match = VERSION.fullmatch(value) if isinstance(value, str) else None
|
||||
if match is None:
|
||||
raise UpdateError("Use a published Coulobre release version.")
|
||||
major, minor, patch, candidate = match.groups()
|
||||
return (
|
||||
int(major),
|
||||
int(minor),
|
||||
int(patch),
|
||||
candidate is None,
|
||||
int(candidate or 0),
|
||||
)
|
||||
|
||||
|
||||
def release_tag(version):
|
||||
version_key(version)
|
||||
base, marker, candidate = version.partition("rc")
|
||||
return f"v{base}-rc.{candidate}" if marker else f"v{base}"
|
||||
|
||||
|
||||
def wheel_name(version):
|
||||
version_key(version)
|
||||
return f"coulobre_panel-{version}-py3-none-any.whl"
|
||||
|
||||
|
||||
def open_project(path):
|
||||
headers = {"User-Agent": "Coulobre Panel updater"}
|
||||
return build_opener(NoRedirect()).open(
|
||||
Request(ORIGIN + path, headers=headers), timeout=8
|
||||
)
|
||||
|
||||
|
||||
def read_json(path, limit=1024 * 1024):
|
||||
try:
|
||||
with open_project(path) as reply:
|
||||
content = reply.read(limit + 1)
|
||||
if len(content) > limit:
|
||||
raise UpdateError("The release response is larger than expected.")
|
||||
return json.loads(content)
|
||||
except (ValueError, OSError, RecursionError) as error:
|
||||
raise UpdateError(
|
||||
"Could not read the published Coulobre release."
|
||||
) from error
|
||||
|
||||
|
||||
def release_asset_path(version, name):
|
||||
return f"/{REPOSITORY}/releases/download/{release_tag(version)}/{name}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Release:
|
||||
version: str
|
||||
notes: str
|
||||
prerelease: bool
|
||||
sha256: str
|
||||
|
||||
|
||||
def compatible_release(item, installed):
|
||||
if not isinstance(item, dict) or item.get("draft") is not False:
|
||||
return None
|
||||
tag = item.get("tag_name")
|
||||
if not isinstance(tag, str) or not tag.startswith("v"):
|
||||
return None
|
||||
version = tag[1:].replace("-rc.", "rc")
|
||||
try:
|
||||
if release_tag(version) != tag or version_key(version) <= version_key(
|
||||
installed
|
||||
):
|
||||
return None
|
||||
except UpdateError:
|
||||
return None
|
||||
assets = item.get("assets")
|
||||
if not isinstance(assets, list):
|
||||
return None
|
||||
names = {
|
||||
asset.get("name")
|
||||
for asset in assets
|
||||
if isinstance(asset, dict) and isinstance(asset.get("name"), str)
|
||||
}
|
||||
if not {MANIFEST, wheel_name(version)} <= names:
|
||||
return None
|
||||
manifest = read_json(release_asset_path(version, MANIFEST), limit=8192)
|
||||
if (
|
||||
not isinstance(manifest, dict)
|
||||
or manifest.get("schema") != 1
|
||||
or manifest.get("version") != version
|
||||
or not isinstance(manifest.get("upgrade_from"), list)
|
||||
or not isinstance(manifest.get("sha256"), str)
|
||||
or not SHA256.fullmatch(manifest["sha256"])
|
||||
):
|
||||
raise UpdateError("The published update manifest is invalid.")
|
||||
if installed not in manifest["upgrade_from"]:
|
||||
return None
|
||||
return Release(
|
||||
version,
|
||||
str(item.get("body") or "")[:12000],
|
||||
"rc" in version or bool(item.get("prerelease")),
|
||||
manifest["sha256"],
|
||||
)
|
||||
|
||||
|
||||
def available_releases(installed):
|
||||
version_key(installed)
|
||||
items = read_json(f"/api/v1/repos/{REPOSITORY}/releases?limit=10")
|
||||
if not isinstance(items, list):
|
||||
raise UpdateError("The release catalog is invalid.")
|
||||
releases = [
|
||||
release
|
||||
for item in items
|
||||
if (release := compatible_release(item, installed))
|
||||
]
|
||||
return sorted(
|
||||
releases,
|
||||
key=lambda release: version_key(release.version),
|
||||
reverse=True,
|
||||
)
|
||||
|
||||
|
||||
def selected_release(version, installed, digest):
|
||||
tag = release_tag(version)
|
||||
item = read_json(f"/api/v1/repos/{REPOSITORY}/releases/tags/{tag}")
|
||||
release = compatible_release(item, installed)
|
||||
if (
|
||||
release is None
|
||||
or release.version != version
|
||||
or release.sha256 != digest
|
||||
):
|
||||
raise UpdateError(
|
||||
"The selected release changed or is incompatible. "
|
||||
"Review the catalog again."
|
||||
)
|
||||
return release
|
||||
|
||||
|
||||
def download_wheel(release, directory):
|
||||
name = wheel_name(release.version)
|
||||
dest = Path(directory) / name
|
||||
digest = hashlib.sha256()
|
||||
total = 0
|
||||
try:
|
||||
with (
|
||||
open_project(release_asset_path(release.version, name)) as reply,
|
||||
dest.open("xb") as output,
|
||||
):
|
||||
while chunk := reply.read(65536):
|
||||
total += len(chunk)
|
||||
if total > MAX_WHEEL:
|
||||
raise UpdateError(
|
||||
"The release package is larger than expected."
|
||||
)
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
except OSError as error:
|
||||
raise UpdateError(
|
||||
"Could not download the Coulobre release package."
|
||||
) from error
|
||||
if digest.hexdigest() != release.sha256:
|
||||
raise UpdateError(
|
||||
"The release package does not match its published checksum."
|
||||
)
|
||||
return dest
|
||||
@@ -0,0 +1,106 @@
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch
|
||||
|
||||
from . import local_update, release_updates
|
||||
from .release_updates import Release, UpdateError
|
||||
|
||||
|
||||
class ReleaseCatalogTests(TestCase):
|
||||
def test_requires_compatible_published_manifest_and_marks_candidates(self):
|
||||
target = "0.10.1rc2"
|
||||
installed = "0.10.1rc1"
|
||||
item = {
|
||||
"draft": False,
|
||||
"tag_name": "v0.10.1-rc.2",
|
||||
"prerelease": False,
|
||||
"assets": [
|
||||
{"name": "web-update.json"},
|
||||
{"name": release_updates.wheel_name(target)},
|
||||
],
|
||||
}
|
||||
manifest = {
|
||||
"schema": 1,
|
||||
"version": target,
|
||||
"upgrade_from": [installed],
|
||||
"sha256": "a" * 64,
|
||||
}
|
||||
with patch(
|
||||
"coulobre.release_updates.read_json", return_value=manifest
|
||||
):
|
||||
release = release_updates.compatible_release(item, installed)
|
||||
self.assertTrue(release.prerelease)
|
||||
self.assertEqual(release.version, target)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(
|
||||
item | {"draft": True}, installed
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(item, "0.10.0rc1")
|
||||
)
|
||||
self.assertIsNone(
|
||||
release_updates.compatible_release(item, "0.10.1")
|
||||
)
|
||||
|
||||
def test_rejects_a_package_with_the_wrong_checksum(self):
|
||||
release = Release(
|
||||
"0.10.1rc2", "", True, hashlib.sha256(b"expected").hexdigest()
|
||||
)
|
||||
with (
|
||||
TemporaryDirectory() as directory,
|
||||
patch(
|
||||
"coulobre.release_updates.open_project",
|
||||
return_value=BytesIO(b"other"),
|
||||
),
|
||||
self.assertRaisesRegex(UpdateError, "published checksum"),
|
||||
):
|
||||
release_updates.download_wheel(release, directory)
|
||||
|
||||
|
||||
class LocalUpdateStatusTests(TestCase):
|
||||
def test_orphaned_running_state_is_visible_after_a_restart(self):
|
||||
with TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
lock = root / "update.lock"
|
||||
lock.touch()
|
||||
with patch.multiple(
|
||||
local_update, STATUS=root / "status.json", LOCK=lock
|
||||
):
|
||||
local_update.publish_status(
|
||||
{}, "running", "Applying migrations."
|
||||
)
|
||||
self.assertEqual(
|
||||
local_update.display_status()["state"], "recovery_required"
|
||||
)
|
||||
with lock.open("a") as active:
|
||||
local_update.fcntl.flock(
|
||||
active, local_update.fcntl.LOCK_EX
|
||||
)
|
||||
self.assertEqual(
|
||||
local_update.display_status()["state"], "running"
|
||||
)
|
||||
|
||||
def test_fails_preflight_before_mutating_packages_or_services(self):
|
||||
with (
|
||||
TemporaryDirectory() as directory,
|
||||
patch(
|
||||
"coulobre.local_update.selected_release",
|
||||
side_effect=UpdateError("Incompatible release."),
|
||||
),
|
||||
patch("coulobre.local_update.run") as commands,
|
||||
):
|
||||
root = Path(directory)
|
||||
with patch.multiple(
|
||||
local_update, STATE=root, STATUS=root / "status.json"
|
||||
):
|
||||
local_update.apply_update(
|
||||
{"installed_version": "0.10.1rc1"},
|
||||
{"version": "0.10.1rc2", "sha256": "a" * 64},
|
||||
"panel.example.net",
|
||||
)
|
||||
self.assertEqual(local_update.read_status()["state"], "failed")
|
||||
self.assertFalse(commands.called)
|
||||
@@ -0,0 +1,40 @@
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Describe a reviewed wheel for the web updater."
|
||||
)
|
||||
parser.add_argument("wheel", type=Path)
|
||||
parser.add_argument("upgrade_from", nargs="+")
|
||||
args = parser.parse_args()
|
||||
version_pattern = r"\d+\.\d+\.\d+(?:rc\d+)?"
|
||||
match = re.fullmatch(
|
||||
rf"coulobre_panel-({version_pattern})-py3-none-any\.whl",
|
||||
args.wheel.name,
|
||||
)
|
||||
if match is None or any(
|
||||
not re.fullmatch(version_pattern, item) for item in args.upgrade_from
|
||||
):
|
||||
parser.error("Use a Coulobre wheel and the tested installed versions.")
|
||||
with args.wheel.open("rb") as wheel:
|
||||
checksum = hashlib.file_digest(wheel, "sha256").hexdigest()
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"version": match[1],
|
||||
"upgrade_from": args.upgrade_from,
|
||||
"sha256": checksum,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user