Gate linked panel upgrades on receiver maintenance and release parity
This commit is contained in:
1 parent
22205f4e4b
commit
2f686b6499
11 files changed
+653
-42
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
import socket
|
||||
from importlib.metadata import version
|
||||
|
||||
from django.views.decorators.debug import sensitive_variables
|
||||
|
||||
@@ -11,8 +12,10 @@ from coulobre.account_restore_request import (
|
||||
RESTORE_SOCKET,
|
||||
RESTORE_TIMEOUT_SECONDS,
|
||||
)
|
||||
from coulobre.linked_updates import ROLES, UNIT_DIR, read_probe
|
||||
from coulobre.mail_dns import dkim_key
|
||||
from coulobre.mail_node import MailboxQuotaUpdate, MailboxSigningRequest
|
||||
from coulobre.node_probe import PROBE_BYTES, parse_status_probe
|
||||
from coulobre.php_pool_settings import PhpPoolSettings
|
||||
from coulobre.php_runtime import validate_php_version
|
||||
from coulobre.web_node import (
|
||||
@@ -250,6 +253,7 @@ def encode_manifest(manifest):
|
||||
def apply_on_local_node(
|
||||
spec, socket_path, node, resource, *, identity=None, timeout=195
|
||||
):
|
||||
require_matching_receiver(socket_path)
|
||||
manifest = spec.manifest()
|
||||
expected = manifest if identity is None else identity
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
|
||||
@@ -284,3 +288,23 @@ def apply_on_local_node(
|
||||
if state == "failed" and isinstance(problem, str) and problem.strip():
|
||||
raise ValueError(problem.strip()[:2000])
|
||||
raise NodeReplyError(invalid_response)
|
||||
|
||||
|
||||
def require_matching_receiver(socket_path):
|
||||
for role in ROLES:
|
||||
unit = f"coulobre-{role}-apply"
|
||||
if str(socket_path) != f"/run/{unit}.sock":
|
||||
continue
|
||||
if not (UNIT_DIR / f"{unit}@.service.d/remote.conf").exists():
|
||||
return
|
||||
try:
|
||||
report = parse_status_probe(read_probe(role, PROBE_BYTES), role)
|
||||
if report["state"] == "configured" and report[
|
||||
"release"
|
||||
] == version("coulobre-panel"):
|
||||
return
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
raise NodeReplyError(
|
||||
f"The linked {role} receiver is not ready for this release."
|
||||
)
|
||||
@@ -3,7 +3,7 @@
|
||||
{% 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>
|
||||
<a class="button secondary" href="{% url 'panel:updates' %}?refresh=1">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 %}
|
||||
@@ -18,17 +18,36 @@
|
||||
</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>
|
||||
<section class="surface"><p class="empty">Enable the local updater socket on an installer-managed panel to use web updates.</p></section>
|
||||
{% elif catalog_problem %}
|
||||
<section class="surface"><p class="empty">{{ catalog_problem }}</p></section>
|
||||
{% else %}
|
||||
{% if preflight_problem %}
|
||||
<section class="surface"><p class="empty">{{ preflight_problem }}</p></section>
|
||||
{% endif %}
|
||||
{% if linked_nodes %}
|
||||
<section class="surface" aria-labelledby="linked-updates">
|
||||
<header class="section-heading"><h2 id="linked-updates">Linked receivers</h2></header>
|
||||
<p class="section-text">Account for every panel using a shared receiver. Stage receivers at the target release in maintenance mode, then upgrade the panels. Resume the receivers when all panels are verified.</p>
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Role</th><th scope="col">Host</th><th scope="col">Release</th><th scope="col">Probe protocol</th><th scope="col">Status</th><th scope="col">Staged target</th></tr></thead>
|
||||
<tbody>
|
||||
{% for node in linked_nodes %}
|
||||
<tr><td>{{ node.role|upper }}</td><td>{{ node.host }}</td><td>{{ node.release|default:"Unknown" }}</td><td>{{ node.protocol|default:"Unknown" }}</td><td>{{ node.state|capfirst }}</td><td>{{ node.upgrade_target|default:"—" }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
{% endif %}
|
||||
<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" %}
|
||||
{% if may_apply and release.version in applyable_versions 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 }}">
|
||||
@@ -37,6 +56,8 @@
|
||||
<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>
|
||||
{% elif linked_nodes and release.version not in applyable_versions %}
|
||||
<p>Stage all linked receivers for this release before installing it.</p>
|
||||
{% endif %}
|
||||
</details>
|
||||
{% empty %}
|
||||
|
||||
@@ -12,7 +12,8 @@ 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.linked_updates import staged_for_release
|
||||
from coulobre.local_update import SOCKET
|
||||
from coulobre.release_updates import (
|
||||
UpdateError,
|
||||
available_releases,
|
||||
@@ -30,6 +31,30 @@ class UpdateForm(forms.Form):
|
||||
)
|
||||
|
||||
|
||||
def request_updater(payload, *, timeout=6):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(timeout)
|
||||
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 isinstance(result, dict) or result.get("accepted") is not True:
|
||||
message = result.get("message") if isinstance(result, dict) else None
|
||||
raise UpdateError(message or "The local updater could not be reached.")
|
||||
return result
|
||||
|
||||
|
||||
def inspect_linked_nodes():
|
||||
try:
|
||||
return request_updater({"action": "linked-nodes"}, timeout=10)
|
||||
except (OSError, ValueError, UpdateError) as error:
|
||||
return {
|
||||
"problem": str(error)
|
||||
if isinstance(error, UpdateError)
|
||||
else "The linked node preflight is unavailable."
|
||||
}
|
||||
|
||||
|
||||
@method_decorator(never_cache, name="dispatch")
|
||||
class UpdateView(UserPassesTestMixin, FormView):
|
||||
form_class = UpdateForm
|
||||
@@ -41,7 +66,6 @@ class UpdateView(UserPassesTestMixin, FormView):
|
||||
|
||||
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:
|
||||
@@ -53,12 +77,33 @@ class UpdateView(UserPassesTestMixin, FormView):
|
||||
return context
|
||||
context["installed_version"] = installed
|
||||
if context["updater_enabled"]:
|
||||
if self.request.GET.get("refresh") == "1":
|
||||
cache.delete(f"coulobre-updates:{installed}")
|
||||
cache.delete("coulobre-update-linked-nodes")
|
||||
topology = cache.get_or_set(
|
||||
"coulobre-update-linked-nodes",
|
||||
inspect_linked_nodes,
|
||||
timeout=30,
|
||||
)
|
||||
nodes = topology.get("nodes", [])
|
||||
context["update_status"] = topology.get("status", {})
|
||||
context["linked_nodes"] = nodes
|
||||
context["preflight_problem"] = topology.get("problem")
|
||||
try:
|
||||
context["releases"] = cache.get_or_set(
|
||||
f"coulobre-updates:{installed}",
|
||||
lambda: available_releases(installed),
|
||||
timeout=300,
|
||||
)
|
||||
if not context["preflight_problem"]:
|
||||
context["applyable_versions"] = {
|
||||
release.version
|
||||
for release in context["releases"]
|
||||
if all(
|
||||
staged_for_release(node, release.version)
|
||||
for node in nodes
|
||||
)
|
||||
}
|
||||
except UpdateError as error:
|
||||
context["catalog_problem"] = str(error)
|
||||
return context
|
||||
@@ -73,14 +118,8 @@ class UpdateView(UserPassesTestMixin, FormView):
|
||||
}
|
||||
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"])
|
||||
request_updater(payload, timeout=10)
|
||||
cache.delete("coulobre-update-linked-nodes")
|
||||
except (OSError, ValueError):
|
||||
form.add_error(
|
||||
None,
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
from .node_files import read_root_file, require_root_directory
|
||||
from .node_probe import (
|
||||
PROBE_BYTES,
|
||||
PROBE_LIMIT,
|
||||
STATUS_PROBE_BYTES,
|
||||
parse_status_probe,
|
||||
)
|
||||
|
||||
ROLES = ("dns", "mail")
|
||||
LOCAL_MODES = {"local", "off"}
|
||||
REMOTE_MODES = {"remote", "remote-install"}
|
||||
RELAY_DIR = Path("/etc/coulobre-remote")
|
||||
UNIT_DIR = Path("/etc/systemd/system")
|
||||
|
||||
|
||||
def relay_is_installed(role):
|
||||
drop_in = UNIT_DIR / f"coulobre-{role}-apply@.service.d/remote.conf"
|
||||
require_root_directory(drop_in.parent)
|
||||
read_root_file(drop_in, mode=0o644)
|
||||
directory = RELAY_DIR / role
|
||||
require_root_directory(directory)
|
||||
for name in ("known_hosts", "ssh_config"):
|
||||
read_root_file(directory / name, mode=0o640)
|
||||
|
||||
|
||||
def read_probe(role, payload):
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||
peer.settimeout(3)
|
||||
peer.connect(f"/run/coulobre-{role}-apply.sock")
|
||||
peer.sendall(payload)
|
||||
peer.shutdown(socket.SHUT_WR)
|
||||
with peer.makefile("rb") as stream:
|
||||
return stream.read(PROBE_LIMIT + 1)
|
||||
|
||||
|
||||
def receiver_status(role, host):
|
||||
status = {
|
||||
"role": role,
|
||||
"host": host,
|
||||
"release": None,
|
||||
"protocol": None,
|
||||
"state": "unavailable",
|
||||
"upgrade_target": None,
|
||||
}
|
||||
try:
|
||||
relay_is_installed(role)
|
||||
body = read_probe(role, STATUS_PROBE_BYTES)
|
||||
try:
|
||||
report = parse_status_probe(body, role)
|
||||
except ValueError:
|
||||
report = parse_status_probe(read_probe(role, PROBE_BYTES), role)
|
||||
except (ValueError, OSError):
|
||||
return status
|
||||
return status | report
|
||||
|
||||
|
||||
def linked_roles(plan):
|
||||
roles = []
|
||||
for role in ROLES:
|
||||
config = plan[role]
|
||||
mode = config["mode"]
|
||||
installed = (
|
||||
UNIT_DIR / f"coulobre-{role}-apply@.service.d/remote.conf"
|
||||
).exists()
|
||||
if mode in REMOTE_MODES:
|
||||
roles.append((role, config["host"]))
|
||||
elif (
|
||||
mode not in LOCAL_MODES or installed or (RELAY_DIR / role).exists()
|
||||
):
|
||||
raise ValueError("Check manually configured linked receivers.")
|
||||
if RELAY_DIR.exists() and any(
|
||||
child.name not in ROLES for child in RELAY_DIR.iterdir()
|
||||
):
|
||||
raise ValueError(
|
||||
"Use the manual procedure for additional remote mail services."
|
||||
)
|
||||
return roles
|
||||
|
||||
|
||||
def staged_for_release(node, target):
|
||||
return (
|
||||
node["protocol"] == 2
|
||||
and node["state"] == "maintenance"
|
||||
and node["release"] == target == node["upgrade_target"]
|
||||
)
|
||||
@@ -15,7 +15,14 @@ from pathlib import Path
|
||||
from pwd import getpwnam
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from .release_updates import UpdateError, download_wheel, selected_release
|
||||
from .linked_updates import linked_roles, receiver_status, staged_for_release
|
||||
from .release_updates import (
|
||||
SHA256,
|
||||
UpdateError,
|
||||
download_wheel,
|
||||
selected_release,
|
||||
version_key,
|
||||
)
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -63,11 +70,6 @@ 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",
|
||||
@@ -90,7 +92,7 @@ def publish_status(status, state, message):
|
||||
with staged.open("w", encoding="utf-8") as stream:
|
||||
json.dump(status, stream)
|
||||
stream.write("\n")
|
||||
os.fchmod(stream.fileno(), 0o644)
|
||||
os.fchmod(stream.fileno(), 0o600)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
staged.replace(STATUS)
|
||||
@@ -138,33 +140,46 @@ def root_controlled(path):
|
||||
)
|
||||
|
||||
|
||||
def check_installation():
|
||||
def installation_plan():
|
||||
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"
|
||||
installation.get("complete") is not True
|
||||
or os.environ.get("COULOBRE_DB_NAME") != "coulobre_panel"
|
||||
or os.environ.get("COULOBRE_DB_HOST") != "/run/mysqld/mysqld.sock"
|
||||
):
|
||||
raise ValueError
|
||||
return installation["plan"]
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise UpdateError(
|
||||
"Web updates require a complete installer-managed panel "
|
||||
"with a local MariaDB database."
|
||||
) from error
|
||||
|
||||
|
||||
def linked_status(plan):
|
||||
try:
|
||||
roles = linked_roles(plan)
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise UpdateError(
|
||||
"Web updates require a complete single-server installation "
|
||||
"with the installer-managed MariaDB database."
|
||||
"Use the manual upgrade procedure for this remote configuration."
|
||||
) from error
|
||||
return [receiver_status(role, host) for role, host in roles]
|
||||
|
||||
|
||||
def check_installation(target):
|
||||
plan = installation_plan()
|
||||
if not all(
|
||||
staged_for_release(node, target) for node in linked_status(plan)
|
||||
):
|
||||
raise UpdateError(
|
||||
"Stage every linked receiver at the selected release before "
|
||||
"upgrading the panel."
|
||||
)
|
||||
return plan["hostname"]
|
||||
|
||||
|
||||
@@ -281,6 +296,26 @@ def back_up(backup, log):
|
||||
raise UpdateError("The database recovery dump is empty.")
|
||||
|
||||
|
||||
def check_dependencies(wheel, log):
|
||||
try:
|
||||
run(
|
||||
PYTHON,
|
||||
"-m",
|
||||
"pip",
|
||||
"--isolated",
|
||||
"install",
|
||||
"--dry-run",
|
||||
"--no-index",
|
||||
wheel,
|
||||
log=log,
|
||||
)
|
||||
except UpdateError:
|
||||
raise UpdateError(
|
||||
"The installed dependencies cannot satisfy this release. "
|
||||
"Use the manual upgrade procedure."
|
||||
) from None
|
||||
|
||||
|
||||
def apply_update(status, request, hostname):
|
||||
backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ")
|
||||
backup.mkdir(mode=0o700)
|
||||
@@ -299,6 +334,8 @@ def apply_update(status, request, hostname):
|
||||
)
|
||||
publish_status(status, "running", "Verifying the release package.")
|
||||
wheel = download_wheel(release, download)
|
||||
check_dependencies(wheel, log)
|
||||
check_installation(release.version)
|
||||
active = active_units(log)
|
||||
if not {PANEL, BEAT, WORKER} <= set(active):
|
||||
raise UpdateError(
|
||||
@@ -417,6 +454,8 @@ def read_request(peer):
|
||||
raise UpdateError("Only the Coulobre panel can request updates.")
|
||||
with peer.makefile("rb") as stream:
|
||||
request = json.loads(stream.readline(2048))
|
||||
if request == {"action": "linked-nodes"}:
|
||||
return request
|
||||
if not isinstance(request, dict) or set(request) != {
|
||||
"version",
|
||||
"sha256",
|
||||
@@ -431,6 +470,9 @@ def read_request(peer):
|
||||
for value in request.values()
|
||||
):
|
||||
raise UpdateError("The update request is invalid.")
|
||||
version_key(request["version"])
|
||||
if not SHA256.fullmatch(request["sha256"]):
|
||||
raise UpdateError("The update request is invalid.")
|
||||
return request
|
||||
|
||||
|
||||
@@ -440,12 +482,25 @@ def reply(peer, **payload):
|
||||
|
||||
def handle_request(peer):
|
||||
request = read_request(peer)
|
||||
if request.get("action") == "linked-nodes":
|
||||
try:
|
||||
nodes = linked_status(installation_plan())
|
||||
except UpdateError as error:
|
||||
reply(
|
||||
peer,
|
||||
accepted=True,
|
||||
status=display_status(),
|
||||
problem=str(error),
|
||||
)
|
||||
else:
|
||||
reply(peer, accepted=True, status=display_status(), nodes=nodes)
|
||||
return
|
||||
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)
|
||||
os.fchmod(lock.fileno(), 0o600)
|
||||
previous = read_status()
|
||||
if previous.get("state") == "running":
|
||||
publish_status(
|
||||
@@ -471,7 +526,7 @@ def handle_request(peer):
|
||||
status["actor"],
|
||||
)
|
||||
try:
|
||||
hostname = check_installation()
|
||||
hostname = check_installation(request["version"])
|
||||
except UpdateError as error:
|
||||
publish_status(status, "failed", str(error))
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import shlex
|
||||
from importlib.metadata import version
|
||||
from pathlib import Path
|
||||
|
||||
from .node_files import (
|
||||
locked_root_directory,
|
||||
read_root_file,
|
||||
require_root_directory,
|
||||
write_new_file,
|
||||
)
|
||||
from .release_updates import UpdateError, version_key
|
||||
|
||||
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
|
||||
|
||||
|
||||
def maintenance_path(role):
|
||||
return NODE_KEYS / f".{role}-upgrade.json"
|
||||
|
||||
|
||||
def rollout_target(role):
|
||||
path = maintenance_path(role)
|
||||
try:
|
||||
path.lstat()
|
||||
require_root_directory(NODE_KEYS)
|
||||
data = json.loads(read_root_file(path, mode=0o600))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if (
|
||||
not isinstance(data, dict)
|
||||
or set(data) != {"target", "panels"}
|
||||
or not isinstance(data["panels"], dict)
|
||||
):
|
||||
raise ValueError("Invalid receiver maintenance record.")
|
||||
try:
|
||||
version_key(data["target"])
|
||||
except UpdateError as error:
|
||||
raise ValueError(str(error)) from None
|
||||
return data["target"]
|
||||
|
||||
|
||||
def receiver_panel_keys(role):
|
||||
require_root_directory(NODE_KEYS)
|
||||
keys = read_root_file(NODE_KEYS / f"coulobre-{role}-request", mode=0o644)
|
||||
fingerprints = set()
|
||||
for line in keys.splitlines():
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
_, key_type, key = shlex.split(line)
|
||||
if key_type != "ssh-ed25519":
|
||||
raise ValueError("Expected an Ed25519 key for every linked panel.")
|
||||
digest = hashlib.sha256(base64.b64decode(key, validate=True)).digest()
|
||||
fingerprint = base64.b64encode(digest).decode().rstrip("=")
|
||||
fingerprints.add(f"SHA256:{fingerprint}")
|
||||
if not fingerprints:
|
||||
raise ValueError("No authorized panel keys were found.")
|
||||
return fingerprints
|
||||
|
||||
|
||||
def verify_inventory(role, source):
|
||||
require_root_directory(source.parent)
|
||||
plan = json.loads(read_root_file(source, mode=0o600))
|
||||
if (
|
||||
not isinstance(plan, dict)
|
||||
or set(plan) != {"target", "panels"}
|
||||
or not isinstance(plan["panels"], dict)
|
||||
or set(plan["panels"]) != receiver_panel_keys(role)
|
||||
):
|
||||
raise ValueError("Account for every authorized panel key in the plan.")
|
||||
try:
|
||||
target = version_key(plan["target"])
|
||||
releases = {
|
||||
version_key(release) for release in plan["panels"].values()
|
||||
}
|
||||
except UpdateError as error:
|
||||
raise ValueError(str(error)) from None
|
||||
if len(releases) != 1:
|
||||
raise ValueError("All linked panels must agree on their release.")
|
||||
return plan, target, releases.pop()
|
||||
|
||||
|
||||
def begin_maintenance(role, source):
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
plan, target, panels = verify_inventory(role, source)
|
||||
receiver = version_key(version("coulobre-panel"))
|
||||
if not panels <= receiver <= target or panels == target:
|
||||
raise ValueError(
|
||||
"Use an upgrade target and the current linked panel versions."
|
||||
)
|
||||
write_new_file(
|
||||
maintenance_path(role), json.dumps(plan) + "\n", mode=0o600
|
||||
)
|
||||
|
||||
|
||||
def finish_maintenance(role, source):
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
plan, target, panels = verify_inventory(role, source)
|
||||
receiver = version("coulobre-panel")
|
||||
if not (
|
||||
rollout_target(role) == plan["target"] == receiver
|
||||
and target == panels
|
||||
):
|
||||
raise ValueError(
|
||||
"The receiver and every linked panel must be at the target."
|
||||
)
|
||||
maintenance_path(role).unlink()
|
||||
@@ -4,6 +4,8 @@ from importlib.metadata import version
|
||||
|
||||
PROBE = {"version": 1, "operation": "probe"}
|
||||
PROBE_BYTES = (json.dumps(PROBE) + "\n").encode()
|
||||
STATUS_PROBE = PROBE | {"version": 2}
|
||||
STATUS_PROBE_BYTES = (json.dumps(STATUS_PROBE) + "\n").encode()
|
||||
PROBE_LIMIT = 4096
|
||||
|
||||
|
||||
@@ -11,6 +13,44 @@ def probe_identity(role):
|
||||
return PROBE | {"role": role, "release": version("coulobre-panel")}
|
||||
|
||||
|
||||
def parse_status_probe(body, role):
|
||||
from .release_updates import UpdateError, version_key
|
||||
|
||||
try:
|
||||
if len(body) > PROBE_LIMIT:
|
||||
raise ValueError
|
||||
reply = json.loads(body)
|
||||
if (
|
||||
not isinstance(reply, dict)
|
||||
or type(reply.get("version")) is not int
|
||||
or reply["version"] not in {1, 2}
|
||||
or reply.get("operation") != "probe"
|
||||
or reply.get("role") != role
|
||||
or reply.get("state")
|
||||
not in {"configured", "maintenance", "failed"}
|
||||
):
|
||||
raise ValueError
|
||||
version_key(reply.get("release"))
|
||||
target = reply.get("upgrade_target")
|
||||
if reply["state"] == "maintenance":
|
||||
if reply["version"] != 2:
|
||||
raise ValueError
|
||||
version_key(target)
|
||||
else:
|
||||
target = None
|
||||
except (ValueError, TypeError, UpdateError, RecursionError) as error:
|
||||
raise ValueError(
|
||||
"The receiver returned no trusted release status."
|
||||
) from error
|
||||
return {
|
||||
"role": role,
|
||||
"protocol": reply["version"],
|
||||
"release": reply["release"],
|
||||
"state": reply["state"],
|
||||
"upgrade_target": target,
|
||||
}
|
||||
|
||||
|
||||
def check_receiver(role):
|
||||
if role == "dns":
|
||||
from .dns_node_apply import RNDC, ZONE_DIRECTORY, run
|
||||
|
||||
@@ -28,13 +28,44 @@ def serve_apply_request(
|
||||
and isinstance(payload, dict)
|
||||
and payload.get("operation") == "probe"
|
||||
):
|
||||
from .node_probe import PROBE, check_receiver, probe_identity
|
||||
from .node_maintenance import rollout_target
|
||||
from .node_probe import (
|
||||
PROBE,
|
||||
STATUS_PROBE,
|
||||
check_receiver,
|
||||
probe_identity,
|
||||
)
|
||||
|
||||
if payload != PROBE or type(payload.get("version")) is not int:
|
||||
raise ValueError("Expected a version 1 node probe.")
|
||||
report = probe_identity(probe_role)
|
||||
if (
|
||||
payload not in (PROBE, STATUS_PROBE)
|
||||
or type(payload.get("version")) is not int
|
||||
):
|
||||
raise ValueError("Expected a supported node probe.")
|
||||
report = probe_identity(probe_role) | {
|
||||
"version": payload["version"]
|
||||
}
|
||||
check_receiver(probe_role)
|
||||
target = rollout_target(probe_role)
|
||||
if target and payload == PROBE:
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
if target:
|
||||
print(
|
||||
json.dumps(
|
||||
report
|
||||
| {
|
||||
"state": "maintenance",
|
||||
"upgrade_target": target,
|
||||
"problem": None,
|
||||
}
|
||||
)
|
||||
)
|
||||
return 0
|
||||
else:
|
||||
if probe_role is not None:
|
||||
from .node_maintenance import rollout_target
|
||||
|
||||
if rollout_target(probe_role):
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
spec = parse_manifest(payload)
|
||||
report = spec.manifest() if identity is None else identity(spec)
|
||||
result = apply(spec)
|
||||
|
||||
@@ -22,11 +22,17 @@ from .node_files import (
|
||||
require_root_directory,
|
||||
write_new_file,
|
||||
)
|
||||
from .node_maintenance import (
|
||||
NODE_KEYS,
|
||||
begin_maintenance,
|
||||
finish_maintenance,
|
||||
receiver_panel_keys,
|
||||
rollout_target,
|
||||
)
|
||||
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
|
||||
from .sftp_keys import read_public_keys
|
||||
|
||||
PANEL_SSH = Path("/etc/coulobre-remote")
|
||||
NODE_KEYS = Path("/etc/ssh/coulobre-node-keys")
|
||||
SSH_DROP_IN = Path("/etc/ssh/sshd_config.d/00-coulobre-node-requests.conf")
|
||||
SYSTEMD = Path("/etc/systemd/system")
|
||||
COMMAND_ENV = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
|
||||
@@ -229,6 +235,8 @@ def one_public_key(path):
|
||||
def authorize_panel(role, key_path):
|
||||
key = one_public_key(key_path)
|
||||
with locked_root_directory(NODE_KEYS):
|
||||
if rollout_target(role.name):
|
||||
raise ValueError("The receiver is in upgrade maintenance.")
|
||||
check_ssh_receiver(role)
|
||||
destination = NODE_KEYS / role.receiver
|
||||
old = (
|
||||
@@ -438,6 +446,22 @@ def ssh_port(value):
|
||||
return port
|
||||
|
||||
|
||||
def check_receiver_drained(role):
|
||||
active = run(
|
||||
"systemctl",
|
||||
"list-units",
|
||||
"--state=active,activating,deactivating",
|
||||
"--no-legend",
|
||||
"--plain",
|
||||
f"{role.unit}.socket",
|
||||
f"{role.unit}@*.service",
|
||||
)
|
||||
if active.strip():
|
||||
raise ValueError(
|
||||
"Stop the receiver socket and let its requests drain."
|
||||
)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(prog="coulobre-node-setup")
|
||||
parser.add_argument("--source", type=Path, default=Path.cwd())
|
||||
@@ -450,6 +474,12 @@ def main(argv=None):
|
||||
("prepare-panel", "Prepare and print the panel's public SSH key."),
|
||||
("authorize-panel", "Authorize a panel public key on this receiver."),
|
||||
("check-receiver", "Check the service configuration on this node."),
|
||||
("list-panels", "List the authorized panel key fingerprints."),
|
||||
("begin-maintenance", "Stage a verified receiver upgrade plan."),
|
||||
(
|
||||
"finish-maintenance",
|
||||
"Verify the final plan and resume the receiver.",
|
||||
),
|
||||
(
|
||||
"enrol-panel",
|
||||
"Verify and install a remote relay on the panel host.",
|
||||
@@ -463,6 +493,8 @@ def main(argv=None):
|
||||
action.add_argument("role", choices=ROLES)
|
||||
if command == "authorize-panel":
|
||||
action.add_argument("public_key", type=Path)
|
||||
if command in {"begin-maintenance", "finish-maintenance"}:
|
||||
action.add_argument("inventory", type=Path)
|
||||
if command == "enrol-panel":
|
||||
action.add_argument("host")
|
||||
action.add_argument("host_key", type=Path)
|
||||
@@ -492,6 +524,18 @@ def main(argv=None):
|
||||
elif args.command == "check-receiver":
|
||||
check_receiver(role.name)
|
||||
print(f"The local {role.name} services are ready.")
|
||||
elif args.command == "list-panels":
|
||||
print("\n".join(sorted(receiver_panel_keys(role.name))))
|
||||
elif args.command == "begin-maintenance":
|
||||
check_ssh_receiver(role)
|
||||
check_receiver_drained(role)
|
||||
begin_maintenance(role.name, args.inventory)
|
||||
print(f"The {role.name} receiver is in upgrade maintenance.")
|
||||
elif args.command == "finish-maintenance":
|
||||
check_ssh_receiver(role)
|
||||
check_receiver(role.name)
|
||||
finish_maintenance(role.name, args.inventory)
|
||||
print(f"The {role.name} receiver is accepting requests.")
|
||||
elif args.command == "enrol-panel":
|
||||
enrol_panel(
|
||||
release_assets(args.source),
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
from unittest import TestCase
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from . import linked_updates, local_update, node_maintenance
|
||||
from .node_probe import PROBE, STATUS_PROBE, parse_status_probe
|
||||
from .node_requests import serve_apply_request
|
||||
from .release_updates import UpdateError
|
||||
|
||||
ORIGINAL = "0.11.0rc1"
|
||||
TARGET = "0.11.1rc1"
|
||||
|
||||
|
||||
def receiver(role, release, *, protocol=2, state="maintenance", target=TARGET):
|
||||
return {
|
||||
"version": protocol,
|
||||
"operation": "probe",
|
||||
"role": role,
|
||||
"release": release,
|
||||
"state": state,
|
||||
"upgrade_target": target,
|
||||
}
|
||||
|
||||
|
||||
class LinkedUpdateTests(TestCase):
|
||||
def test_only_target_version_in_maintenance_enables_update(self):
|
||||
def staged(body):
|
||||
return linked_updates.staged_for_release(
|
||||
parse_status_probe(json.dumps(body).encode(), "dns"), TARGET
|
||||
)
|
||||
|
||||
self.assertTrue(staged(receiver("dns", TARGET)))
|
||||
self.assertFalse(staged(receiver("dns", ORIGINAL)))
|
||||
self.assertFalse(staged(receiver("dns", TARGET, state="configured")))
|
||||
self.assertFalse(staged(receiver("dns", TARGET, target="0.11.2rc1")))
|
||||
self.assertFalse(
|
||||
staged(receiver("dns", TARGET, protocol=1, state="configured"))
|
||||
)
|
||||
|
||||
def test_roster_requires_every_shared_panel_before_leaving_maintenance(
|
||||
self,
|
||||
):
|
||||
with TemporaryDirectory() as root:
|
||||
inventory = Path(root) / "inventory.json"
|
||||
state = Path(root) / "keys"
|
||||
state.mkdir()
|
||||
keys = {"SHA256:panel-one", "SHA256:panel-two"}
|
||||
|
||||
def write_plan(panels):
|
||||
inventory.write_text(
|
||||
json.dumps({"target": TARGET, "panels": panels})
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(node_maintenance, "NODE_KEYS", state),
|
||||
patch.object(node_maintenance, "locked_root_directory"),
|
||||
patch.object(node_maintenance, "require_root_directory"),
|
||||
patch.object(
|
||||
node_maintenance,
|
||||
"read_root_file",
|
||||
side_effect=Path.read_text,
|
||||
) as read,
|
||||
patch.object(
|
||||
node_maintenance, "receiver_panel_keys", return_value=keys
|
||||
),
|
||||
patch.object(
|
||||
node_maintenance, "version", return_value=ORIGINAL
|
||||
) as release,
|
||||
):
|
||||
read.side_effect = lambda path, mode: path.read_text()
|
||||
write_plan({key: ORIGINAL for key in keys})
|
||||
node_maintenance.begin_maintenance("dns", inventory)
|
||||
self.assertEqual(
|
||||
node_maintenance.rollout_target("dns"), TARGET
|
||||
)
|
||||
release.return_value = TARGET
|
||||
|
||||
write_plan({"SHA256:panel-one": TARGET})
|
||||
with self.assertRaisesRegex(
|
||||
ValueError, "every authorized panel"
|
||||
):
|
||||
node_maintenance.finish_maintenance("dns", inventory)
|
||||
|
||||
write_plan(
|
||||
{"SHA256:panel-one": TARGET, "SHA256:panel-two": ORIGINAL}
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "agree"):
|
||||
node_maintenance.finish_maintenance("dns", inventory)
|
||||
self.assertEqual(
|
||||
node_maintenance.rollout_target("dns"), TARGET
|
||||
)
|
||||
|
||||
write_plan({key: TARGET for key in keys})
|
||||
node_maintenance.finish_maintenance("dns", inventory)
|
||||
self.assertIsNone(node_maintenance.rollout_target("dns"))
|
||||
|
||||
def test_unknown_receiver_blocks_root_update_until_it_reports_target(self):
|
||||
nodes = [
|
||||
{
|
||||
"protocol": 2,
|
||||
"state": "maintenance",
|
||||
"release": TARGET,
|
||||
"upgrade_target": TARGET,
|
||||
},
|
||||
{
|
||||
"protocol": None,
|
||||
"state": "unavailable",
|
||||
"release": None,
|
||||
"upgrade_target": None,
|
||||
},
|
||||
]
|
||||
with (
|
||||
patch.object(
|
||||
local_update,
|
||||
"installation_plan",
|
||||
return_value={"hostname": "panel.example.test"},
|
||||
),
|
||||
patch.object(local_update, "linked_status", return_value=nodes),
|
||||
):
|
||||
with self.assertRaisesRegex(UpdateError, "every linked receiver"):
|
||||
local_update.check_installation(TARGET)
|
||||
nodes[1].update(nodes[0])
|
||||
self.assertEqual(
|
||||
local_update.check_installation(TARGET), "panel.example.test"
|
||||
)
|
||||
|
||||
def test_receiver_preserves_probe_and_blocks_provisioning_in_maintenance(
|
||||
self,
|
||||
):
|
||||
parse = Mock()
|
||||
apply = Mock()
|
||||
inputs = [
|
||||
STATUS_PROBE,
|
||||
PROBE,
|
||||
{"kind": "bind9_zone", "domain": "example.test", "version": 1},
|
||||
]
|
||||
expected = ["maintenance", "failed", "failed"]
|
||||
for payload, outcome in zip(inputs, expected, strict=True):
|
||||
with (
|
||||
patch(
|
||||
"coulobre.node_requests.sys.stdin",
|
||||
buffer=io.BytesIO(json.dumps(payload).encode()),
|
||||
),
|
||||
patch("sys.stdout", new_callable=io.StringIO) as output,
|
||||
patch("coulobre.node_probe.check_receiver"),
|
||||
patch("coulobre.node_probe.version", return_value=TARGET),
|
||||
patch(
|
||||
"coulobre.node_maintenance.rollout_target",
|
||||
return_value=TARGET,
|
||||
),
|
||||
):
|
||||
result = serve_apply_request(1, parse, apply, probe_role="dns")
|
||||
self.assertEqual(result, int(outcome == "failed"))
|
||||
self.assertEqual(
|
||||
json.loads(output.getvalue())["state"], outcome
|
||||
)
|
||||
parse.assert_not_called()
|
||||
apply.assert_not_called()
|
||||
Reference in new issue
Block a user