Files
coulobre/src/coulobre/local_update.py
T

552 lines
17 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, receiver_status, staged_for_release
from .release_updates import (
SHA256,
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"
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")
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(), 0o600)
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)
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():
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 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):
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)
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 == {"action": "linked-nodes"}:
return request
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.")
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_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(), 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:
message = (
str(error)
if isinstance(error, UpdateError)
else "Could not accept the update request."
)
with suppress(OSError):
reply(peer, accepted=False, message=message)