Files
coulobre/src/coulobre/local_update.py
T

706 lines
23 KiB
Python

import fcntl
import json
import logging
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 .linked_updates import (
linked_roles,
node_inventory,
receiver_status,
staged_for_release,
)
from .release_updates import (
SHA256,
Release,
UpdateError,
download_wheel,
selected_release,
version_key,
)
LOGGER = logging.getLogger(__name__)
SOCKET = Path("/run/coulobre-update.sock")
STATE = Path("/var/lib/coulobre-update")
STATUS = STATE / "status.json"
LOCK = STATE / "update.lock"
APT_STATUS = STATE / "apt-status.json"
APT_LOCK = STATE / "apt.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-mail-passwords.socket",
"coulobre-mailbox-import-worker.service",
"coulobre-mailbox-provisioner.service",
"coulobre-offsite-worker.service",
"coulobre-operator-apply.socket",
"coulobre-operator-worker.service",
"coulobre-remote-deploy.socket",
"coulobre-folder-sftp.socket",
"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")
DEB_WHEEL = Path("/usr/share/coulobre-panel/wheel")
ROOT_COMMAND_ENV = {
"PATH": "/usr/sbin:/usr/bin:/sbin:/bin",
"LC_ALL": "C.UTF-8",
}
def read_status(path=None):
try:
payload = json.loads((path or STATUS).read_text())
return payload if isinstance(payload, dict) else {}
except (OSError, ValueError):
return {}
def publish_status(status, state, message, *, path=None):
path = path or STATUS
status.update(
state=state, message=message, updated_at=datetime.now(UTC).isoformat()
)
staged = path.with_suffix(".new")
with staged.open("w", encoding="utf-8") as stream:
json.dump(status, stream)
stream.write("\n")
os.fchmod(stream.fileno(), 0o600)
stream.flush()
os.fsync(stream.fileno())
staged.replace(path)
directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
if state != "running":
LOGGER.info(
"Update %s for %s requested by %s. %s",
state,
status.get("target_version"),
status.get("actor"),
message,
)
def display_status(*, path=None, lock_path=None):
status = read_status(path)
if status.get("state") == "running":
try:
with (lock_path or LOCK).open("rb") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
status = read_status(path)
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 installation_plan():
try:
if not all(
root_controlled(path) for path in (VENV, CONFIG, INSTALLATION)
):
raise ValueError
installation = json.loads(INSTALLATION.read_text())
if (
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(
"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"]
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 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, *, package_wheel=None):
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:
publish_status(status, "running", "Verifying the release package.")
if package_wheel is None:
release = selected_release(
request["version"],
status["installed_version"],
request["sha256"],
)
wheel = download_wheel(release, download)
else:
release = Release(request["version"], "", False, "")
wheel = package_wheel
check_dependencies(wheel, log)
check_installation(release.version)
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 request in ({"action": "linked-nodes"}, {"action": "node-inventory"}):
return request
if not isinstance(request, dict):
raise UpdateError("The update request is invalid.")
apt = (
set(request) == {"action", "sha256", "actor"}
and request.get("action") == "apt-update"
)
if not apt and 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.")
if not apt:
version_key(request["version"])
if not SHA256.fullmatch(request["sha256"]):
raise UpdateError("The update request is invalid.")
return request
def reply(peer, **payload):
peer.sendall(json.dumps(payload).encode() + b"\n")
def handle_apt_update(peer, request):
from .node_files import locked_root_directory
from .operator_node import APT, PANEL_PACKAGE, apt_plan
from .operator_node import STATE as OPERATOR_STATE
if not DEB_WHEEL.is_dir():
raise UpdateError("Coulobre is not managed by APT.")
if os.environ.get("COULOBRE_SERVER_PACKAGE_UPDATES") != "1":
raise UpdateError("Enable package updates in the host configuration.")
with APT_LOCK.open("a") as lock:
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError as error:
raise UpdateError("An APT update is already running.") from error
if read_status(APT_STATUS).get("state") == "running":
raise UpdateError("Check the interrupted APT update on the host.")
with locked_root_directory(OPERATOR_STATE, blocking=False):
if display_status().get("state") in {
"running",
"recovery_required",
}:
raise UpdateError(
"Resolve the previous update before retrying."
)
try:
# APT extracts the signed index during simulation.
with TemporaryDirectory(dir=STATE) as preview_directory:
plan = apt_plan(
coulobre=True, temp_directory=preview_directory
)
except ValueError as error:
raise UpdateError(str(error)) from error
target = plan["target_version"]
if not target or plan["fingerprint"] != request["sha256"]:
raise UpdateError(
"The APT package plan changed. Review a new preview."
)
if plan["count"] != 1:
raise UpdateError(
"This release changes other packages. Upgrade from the "
"server console after reviewing the package plan."
)
release = target.replace("~rc", "rc")
installed = version("coulobre-panel")
if version_key(release) <= version_key(installed):
raise UpdateError(
"APT did not offer a newer Coulobre version."
)
check_installation(release)
status = {
"installed_version": installed,
"target_version": target,
"actor": request["actor"],
}
publish_status(
status, "running", "Applying the APT package.", path=APT_STATUS
)
with suppress(OSError):
reply(peer, accepted=True)
peer.close()
try:
with (STATE / "apt-update.log").open("wb") as log:
run(
"/usr/bin/systemd-run",
"--quiet",
"--wait",
"--pipe",
"--collect",
"--unit=coulobre-apt-update",
"--property=RuntimeMaxSec=45min",
"--setenv=DEBIAN_FRONTEND=noninteractive",
APT,
"--yes",
"--no-remove",
"--only-upgrade",
"-o",
"Dpkg::Options::=--force-confold",
"install",
f"{PANEL_PACKAGE}={target}",
log=log,
stdout=log,
timeout=2800,
)
if read_status().get("installed_version") != release:
raise UpdateError("The panel did not confirm this update.")
except (OSError, UpdateError):
publish_status(
status,
"failed",
"APT did not finish the Coulobre update. "
"See the private apt-update.log on the server.",
path=APT_STATUS,
)
else:
status["installed_version"] = release
publish_status(
status,
"succeeded",
"Coulobre was updated through APT.",
path=APT_STATUS,
)
def handle_request(peer):
request = read_request(peer)
if request.get("action") == "node-inventory":
try:
nodes = node_inventory(installation_plan())
except (UpdateError, OSError, TypeError, KeyError, ValueError):
reply(
peer,
accepted=True,
nodes=[],
problem="The configured service inventory is unavailable.",
)
else:
reply(peer, accepted=True, nodes=nodes)
return
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,
apt_managed=DEB_WHEEL.is_dir(),
apt_status=display_status(path=APT_STATUS, lock_path=APT_LOCK)
if DEB_WHEEL.is_dir()
else {},
)
return
if request.get("action") == "apt-update":
handle_apt_update(peer, request)
return
if DEB_WHEEL.is_dir():
raise UpdateError("Upgrade this APT-managed panel from the host.")
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(), 0o600)
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"],
}
LOGGER.info(
"Update from %s to %s requested by %s.",
installed,
status["target_version"],
status["actor"],
)
try:
hostname = check_installation(request["version"])
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():
logging.basicConfig(level=logging.INFO, format="%(message)s")
with socket.socket(fileno=0) as peer:
try:
handle_request(peer)
except (OSError, ValueError, UpdateError) as error:
if isinstance(error, UpdateError):
message = str(error)
elif isinstance(error, BlockingIOError):
message = "Wait for the current operator action to finish."
else:
message = "Could not accept the update request."
with suppress(OSError):
reply(peer, accepted=False, message=message)