Guide full-service installs and report installer progress

This commit is contained in:
parkel committed 2026-11-22 21:27:29 +01:00
1 parent e68e54288f
commit 23adbe7b2d
4 files changed
+299 -53

No files matched your search

+165 -34
View File
@@ -1,7 +1,10 @@
import argparse import argparse
import json
import os import os
import sys import sys
from getpass import getpass from getpass import getpass
from pathlib import Path
from tempfile import TemporaryDirectory
from .config import ( from .config import (
REMOTE_MODES, REMOTE_MODES,
@@ -27,55 +30,99 @@ def number(value, label):
raise InstallError(f"Enter a numeric port for {label}.") from None raise InstallError(f"Enter a numeric port for {label}.") from None
def interactive_plan(): def interactive_plan(previous=None):
panel = {"hostname": prompt("Panel hostname")} if previous is None:
access = panel["access"] = prompt( preset = prompt(
"Panel access (tls, acme, or proxy)", "tls" "Installation profile (full-service or custom)", "full-service"
)
if preset not in {"full-service", "custom"}:
raise InstallError("Choose full-service or custom.")
defaults = {}
else:
preset = "custom"
defaults = export_parameters(previous, None)
def ask(label, section, name, fallback=""):
return prompt(
label, str(defaults.get(section, {}).get(name, fallback))
)
full_service = preset == "full-service"
panel = {"hostname": ask("Panel hostname", "panel", "hostname")}
access = panel["access"] = ask(
"Panel access (tls, acme, or proxy)",
"panel",
"access",
"acme" if full_service else "tls",
) )
if access == "tls": if access == "tls":
panel["certificate"] = prompt("Panel certificate path") panel["certificate"] = ask(
panel["key"] = prompt("Panel private key path") "Panel certificate path", "panel", "certificate"
)
panel["key"] = ask("Panel private key path", "panel", "key")
elif access == "proxy": elif access == "proxy":
panel["origin_ip"] = prompt("Private origin address") panel["origin_ip"] = ask(
panel["proxy_ip"] = prompt("Trusted proxy address") "Private origin address", "panel", "origin_ip"
)
panel["proxy_ip"] = ask("Trusted proxy address", "panel", "proxy_ip")
panel["origin_port"] = number( panel["origin_port"] = number(
prompt("Origin port", "8080"), "the origin" ask("Origin port", "panel", "origin_port", "8080"), "the origin"
) )
data = { data = {
"panel": panel, "panel": panel,
"admin": { "admin": {
"username": prompt("Administrator username", "operator"), "username": ask(
"email": prompt("Administrator email"), "Administrator username", "admin", "username", "operator"
),
"email": ask("Administrator email", "admin", "email"),
}, },
} }
for name in ("dns", "mail"): for name in ("dns", "mail"):
mode = prompt( mode = ask(
f"{name.upper()} role (off, local, remote, or remote-install)", f"{name.upper()} role (off, local, remote, or remote-install)",
"off", name,
"mode",
"local" if full_service else "off",
) )
target = data[name] = {"mode": mode} target = data[name] = {"mode": mode}
if mode in REMOTE_MODES: if mode in REMOTE_MODES:
target["host"] = prompt( target["host"] = ask(
f"{name.upper()} node SSH hostname or address" f"{name.upper()} node SSH hostname or address", name, "host"
) )
target["port"] = number( target["port"] = number(
prompt("SSH port", "22"), f"the {name} node" ask("SSH port", name, "port", "22"), f"the {name} node"
)
target["host_key"] = ask(
"Verified SSH host public key file", name, "host_key"
) )
target["host_key"] = prompt("Verified SSH host public key file")
if mode == "remote-install": if mode == "remote-install":
target["ssh_user"] = prompt("SSH administrator username") target["ssh_user"] = ask(
target["ssh_identity"] = prompt( "SSH administrator username", name, "ssh_user"
"SSH administrator private key file" )
target["ssh_identity"] = ask(
"SSH administrator private key file", name, "ssh_identity"
) )
if name == "mail" and mode in {"local", "remote-install"}: if name == "mail" and mode in {"local", "remote-install"}:
field = "host" if mode == "local" else "mail_hostname" field = "host" if mode == "local" else "mail_hostname"
target[field] = prompt("Public mail hostname") target[field] = ask(
target["tls"] = prompt("Mail TLS (provided or acme)", "provided") "Public mail hostname",
if target["tls"] == "provided": name,
target["certificate"] = prompt( field,
"Certificate path on the mail host" panel["hostname"] if mode == "local" else "",
)
target["tls"] = ask(
"Mail TLS (provided or acme)",
name,
"tls",
"acme" if access == "acme" and mode == "local" else "provided",
)
if target["tls"] == "provided":
target["certificate"] = ask(
"Certificate path on the mail host", name, "certificate"
)
target["key"] = ask(
"Private key path on the mail host", name, "key"
) )
target["key"] = prompt("Private key path on the mail host")
return parse_plan(data) return parse_plan(data)
@@ -86,10 +133,81 @@ def get_password(path):
raise InstallError( raise InstallError(
"Use a terminal or provide a private password file." "Use a terminal or provide a private password file."
) )
while True:
try:
password = check_password(getpass("Administrator password: ")) password = check_password(getpass("Administrator password: "))
if getpass("Repeat the administrator password: ") != password: if getpass("Repeat the administrator password: ") == password:
raise InstallError("The administrator passwords differ.")
return password return password
raise InstallError("The administrator passwords differ.")
except InstallError as error:
print(error, file=sys.stderr)
def export_parameters(plan, password_path):
panel = {"hostname": plan.hostname, "access": plan.access}
if plan.access == "tls":
panel.update(certificate=plan.certificate, key=plan.key)
elif plan.access == "proxy":
panel.update(
origin_ip=plan.origin_ip,
origin_port=plan.origin_port,
proxy_ip=plan.proxy_ip,
)
admin = {"username": plan.admin_username, "email": plan.admin_email}
if password_path:
admin["password_file"] = password_path
parameters = {"panel": panel, "admin": admin}
for name, role in (("dns", plan.dns), ("mail", plan.mail)):
fields = parameters[name] = {"mode": role.mode}
if role.mode in REMOTE_MODES:
fields.update(
host=role.host, host_key=role.host_key, port=role.port
)
if role.mode == "remote-install":
fields.update(
ssh_user=role.ssh_user, ssh_identity=role.ssh_identity
)
if name == "mail" and role.mode in {"local", "remote-install"}:
host_key = "host" if role.mode == "local" else "mail_hostname"
fields[host_key] = role.mail_hostname
fields["tls"] = role.tls
if role.tls == "provided":
fields.update(certificate=role.certificate, key=role.key)
return parameters
def save_interactive_plan(plan, password_path):
destination = prompt("Save settings to a TOML path (Enter to skip)")
if not destination:
return
path = Path(destination).expanduser()
exists = os.path.lexists(path)
if exists and prompt(f"Replace {path} (yes or no)", "no") != "yes":
return
with TemporaryDirectory(dir=path.parent) as directory:
temporary = Path(directory) / "installation.toml"
with temporary.open("w", encoding="utf-8") as output:
temporary.chmod(0o600)
for section, fields in export_parameters(
plan, password_path
).items():
output.write(f"[{section}]\n")
for name, value in fields.items():
encoded = json.dumps(value, ensure_ascii=False).replace(
"\x7f", "\\u007f"
)
output.write(f"{name} = {encoded}\n")
output.write("\n")
if exists:
os.replace(temporary, path)
else:
os.link(temporary, path)
print(f"Saved installation settings to {path}.")
if not password_path:
print(
"Provide a private administrator password file "
"when reusing the plan."
)
def main(argv=None): def main(argv=None):
@@ -154,19 +272,32 @@ def main(argv=None):
) )
password = read_password(password_path) password = read_password(password_path)
else: else:
plan = interactive_plan() plan = None
while True:
plan = interactive_plan(plan)
print(plan.description(), flush=True) print(plan.description(), flush=True)
if ( if plan.access == "acme" or plan.mail.tls == "acme":
prompt("Install with these settings (yes or no)", "no").lower() print(
!= "yes" "Let's Encrypt requires public DNS and inbound HTTP "
): "for each selected hostname."
)
decision = prompt(
"Install with these settings (yes, edit, or no)", "no"
).lower()
if decision != "edit":
break
if decision != "yes":
return 0 return 0
save_interactive_plan(plan, options.admin_password_file)
password = get_password(options.admin_password_file) password = get_password(options.admin_password_file)
if options.check: if options.check:
print(plan.description()) print(plan.description())
return 0 return 0
installer = Installer( installer = Installer(
plan, password, lambda message: print(message, flush=True) plan,
password,
lambda message: print(message, flush=True),
heartbeat=sys.stdout.isatty(),
) )
installer.install() installer.install()
return 0 return 0
+48 -9
View File
@@ -10,9 +10,10 @@ import subprocess
import sys import sys
import time import time
import tomllib import tomllib
from contextlib import contextmanager from contextlib import contextmanager, nullcontext
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from threading import Event, Thread
from . import certificates, roles from . import certificates, roles
from .config import REMOTE_MODES, InstallError, platform_settings from .config import REMOTE_MODES, InstallError, platform_settings
@@ -198,7 +199,7 @@ def systemctl(*args):
) )
def install_packages(packages, *, mail_host=""): def install_packages(packages, *, mail_host="", step=nullcontext):
status = subprocess.run( status = subprocess.run(
["dpkg-query", "-W", "-f=${db:Status-Status} ${Package}\n", *packages], ["dpkg-query", "-W", "-f=${db:Status-Status} ${Package}\n", *packages],
stdin=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
@@ -224,6 +225,7 @@ def install_packages(packages, *, mail_host=""):
source=answers.encode(), source=answers.encode(),
label="Choose the local Postfix installation profile", label="Choose the local Postfix installation profile",
) )
with step("Refreshing APT repositories"):
run( run(
"apt-get", "apt-get",
"update", "update",
@@ -231,6 +233,7 @@ def install_packages(packages, *, mail_host=""):
env=apt_env, env=apt_env,
timeout=600, timeout=600,
) )
with step("Installing system packages"):
run( run(
"apt-get", "apt-get",
"install", "install",
@@ -243,7 +246,7 @@ def install_packages(packages, *, mail_host=""):
) )
def install_release(release): def install_release(release, *, step=nullcontext):
root_directory(VENV.parent) root_directory(VENV.parent)
if os.path.lexists(VENV): if os.path.lexists(VENV):
root_directory(VENV) root_directory(VENV)
@@ -276,6 +279,7 @@ def install_release(release):
for key in ("PIP_NO_INDEX", "PIP_FIND_LINKS") for key in ("PIP_NO_INDEX", "PIP_FIND_LINKS")
if key in os.environ if key in os.environ
} }
with step("Installing Coulobre and its Python dependencies"):
run( run(
BINDIR / "pip", BINDIR / "pip",
"install", "install",
@@ -308,15 +312,45 @@ def install_lock():
class Installer: class Installer:
def __init__(self, plan, password, progress): def __init__(self, plan, password, progress, *, heartbeat=False):
self.plan = plan self.plan = plan
self.password = password self.password = password
self.progress = progress self.progress = progress
self.heartbeat = heartbeat
self.state_file = STATE / "installation.json" self.state_file = STATE / "installation.json"
self.php, self.modern_mail = platform_settings() self.php, self.modern_mail = platform_settings()
with (SOURCE / "pyproject.toml").open("rb") as project: with (SOURCE / "pyproject.toml").open("rb") as project:
self.release = tomllib.load(project)["project"]["version"] self.release = tomllib.load(project)["project"]["version"]
@contextmanager
def step(self, label):
started = time.monotonic()
finished = Event()
self.progress(f"{label}.")
def report_elapsed():
while not finished.wait(15):
elapsed = int(time.monotonic() - started)
self.progress(f"{label}… {elapsed}s elapsed.")
thread = Thread(target=report_elapsed) if self.heartbeat else None
if thread is not None:
thread.start()
try:
yield
except (InstallError, OSError, ValueError):
self.progress(
f"{label} failed after {int(time.monotonic() - started)}s."
)
raise
finally:
finished.set()
if thread is not None:
thread.join()
self.progress(
f"{label} completed in {int(time.monotonic() - started)}s."
)
def save_state(self): def save_state(self):
put_file( put_file(
self.state_file, self.state_file,
@@ -421,10 +455,13 @@ class Installer:
"Environment=RABBITMQ_CONFIG_FILE=/etc/coulobre-rabbitmq.conf\n", "Environment=RABBITMQ_CONFIG_FILE=/etc/coulobre-rabbitmq.conf\n",
) )
systemctl("daemon-reload") systemctl("daemon-reload")
systemctl( for name, unit in (
"enable", "--now", "mariadb.service", "rabbitmq-server.service" ("MariaDB", "mariadb.service"),
) ("RabbitMQ", "rabbitmq-server.service"),
systemctl("restart", "mariadb.service", "rabbitmq-server.service") ):
with self.step(f"Starting {name} on loopback"):
systemctl("enable", "--now", unit)
systemctl("restart", unit)
def mariadb(sql): def mariadb(sql):
return run( return run(
@@ -679,10 +716,12 @@ class Installer:
install_packages( install_packages(
self.packages(), self.packages(),
mail_host=mail.host if mail.mode == "local" else "", mail_host=mail.host if mail.mode == "local" else "",
step=self.step,
) )
install_release(self.release) install_release(self.release, step=self.step)
self.install_certificates() self.install_certificates()
self.progress("Preparing MariaDB and RabbitMQ on loopback.") self.progress("Preparing MariaDB and RabbitMQ on loopback.")
with self.step("Configuring database and message broker access"):
self.configure_stores() self.configure_stores()
self.progress( self.progress(
"Configuring hosting service identities and provisioning." "Configuring hosting service identities and provisioning."
+63 -10
View File
@@ -1,4 +1,5 @@
import hmac import hmac
import re
import secrets import secrets
import time import time
from dataclasses import dataclass, field from dataclasses import dataclass, field
@@ -15,11 +16,14 @@ from .engine import Installer
COOKIE = "coulobre_installer" COOKIE = "coulobre_installer"
MAX_FORM = 16384 MAX_FORM = 16384
FORM = """<form method="post" action="/review"> FORM = """<form method="post" action="/review">
<p>Full-service setup is recommended for a public single server. The panel,
websites, databases, DNS and mail run locally. Adjust the settings below
for a different deployment.</p>
<fieldset><legend>Panel</legend> <fieldset><legend>Panel</legend>
<label>Hostname<input name="hostname" autocomplete="off" required></label> <label>Hostname<input name="hostname" autocomplete="off" required></label>
<label>Access<select name="access"> <label>Access<select name="access">
<option value="tls">HTTPS on this server</option>
<option value="acme">HTTPS with Let's Encrypt</option> <option value="acme">HTTPS with Let's Encrypt</option>
<option value="tls">HTTPS on this server</option>
<option value="proxy">Trusted external HTTPS proxy</option></select></label> <option value="proxy">Trusted external HTTPS proxy</option></select></label>
<label>Panel certificate path<input name="certificate"></label> <label>Panel certificate path<input name="certificate"></label>
<label>Panel private key path<input name="key"></label> <label>Panel private key path<input name="key"></label>
@@ -49,8 +53,9 @@ def role_form(name):
"<label>Public mail hostname" "<label>Public mail hostname"
'<input name="mail_local_host"></label>' '<input name="mail_local_host"></label>'
'<label>Mail TLS<select name="mail_tls">' '<label>Mail TLS<select name="mail_tls">'
'<option value="acme">Let&#39;s Encrypt</option>'
'<option value="provided">Existing certificate</option>' '<option value="provided">Existing certificate</option>'
'<option value="acme">Let&#39;s Encrypt</option></select></label>' "</select></label>"
"<label>Certificate path on the mail host" "<label>Certificate path on the mail host"
'<input name="mail_certificate"></label>' '<input name="mail_certificate"></label>'
"<label>Private key path on the mail host" "<label>Private key path on the mail host"
@@ -59,8 +64,9 @@ def role_form(name):
else "" else ""
) )
return f"""<fieldset><legend>{title}</legend> return f"""<fieldset><legend>{title}</legend>
<label>Role<select name="{name}_mode"><option value="off">Disabled</option> <label>Role<select name="{name}_mode">
<option value="local">Local service</option> <option value="local">Local service</option>
<option value="off">Disabled</option>
<option value="remote">Connect an existing Coulobre node</option> <option value="remote">Connect an existing Coulobre node</option>
<option value="remote-install">Install and connect a Coulobre node</option> <option value="remote-install">Install and connect a Coulobre node</option>
</select></label> </select></label>
@@ -117,7 +123,9 @@ def form_plan(fields):
) )
if name == "mail" and mode in {"local", "remote-install"}: if name == "mail" and mode in {"local", "remote-install"}:
field = "host" if mode == "local" else "mail_hostname" field = "host" if mode == "local" else "mail_hostname"
target[field] = fields.get("mail_local_host", "") target[field] = fields.get("mail_local_host") or (
panel["hostname"] if mode == "local" else ""
)
target["tls"] = fields.get("mail_tls", "provided") target["tls"] = fields.get("mail_tls", "provided")
if target["tls"] == "provided": if target["tls"] == "provided":
target.update( target.update(
@@ -127,6 +135,30 @@ def form_plan(fields):
return parse_plan(data) return parse_plan(data)
def installation_form(values):
html = FORM.format(dns=role_form("dns"), mail=role_form("mail"))
def restore_field(match):
tag = match[0]
name = match["input"] or match["select"]
if name not in values:
return tag
value = values[name]
if tag.startswith("<input"):
tag = re.sub(r' value="[^"]*"', "", tag)
return f'{tag[:-1]} value="{escape(value, quote=True)}">'
options = f'<option value="{escape(value, quote=True)}"'
return tag.replace(options + ">", options + " selected>")
return re.sub(
r'<input name="(?P<input>[a-z_]+)"[^>]*>|'
r'<select name="(?P<select>[a-z_]+)">.*?</select>',
restore_field,
html,
flags=re.DOTALL,
)
@dataclass @dataclass
class Wizard: class Wizard:
password: str = field(repr=False) password: str = field(repr=False)
@@ -135,12 +167,15 @@ class Wizard:
) )
session: str = field(default="", repr=False) session: str = field(default="", repr=False)
pending: object = None pending: object = None
form_values: dict[str, str] = field(default_factory=dict, repr=False)
thread: Thread | None = None thread: Thread | None = None
progress: list[str] = field(default_factory=list) progress: list[str] = field(default_factory=list)
progress_at: float | None = None
finished: float | None = None finished: float | None = None
error: str = "" error: str = ""
def report(self, text): def report(self, text):
self.progress_at = time.monotonic()
self.progress.append(text) self.progress.append(text)
print(text, flush=True) print(text, flush=True)
@@ -229,19 +264,36 @@ class WizardHandler(BaseHTTPRequestHandler):
) )
self.page(f"<ol>{steps}") self.page(f"<ol>{steps}")
else: else:
self.page(f"<ol>{steps}</ol>", refresh=state.finished is None) elapsed = ""
elif state.pending is not None: if state.finished is None and state.progress_at is not None:
seconds = int(time.monotonic() - state.progress_at)
elapsed = (
f'<p role="status">Working for {seconds}s '
"since the last update.</p>"
)
self.page( self.page(
f"<p>{escape(state.pending.description())}</p>" f"<ol>{steps}</ol>{elapsed}",
refresh=state.finished is None,
)
elif state.pending is not None:
prerequisites = ""
if (
state.pending.access == "acme"
or state.pending.mail.tls == "acme"
):
prerequisites = (
"<p>Let's Encrypt requires public DNS and inbound HTTP "
"for each selected hostname.</p>"
)
self.page(
f"<p>{escape(state.pending.description())}</p>{prerequisites}"
'<form method="post" action="/install">' '<form method="post" action="/install">'
'<button type="submit">Install Coulobre</button></form>' '<button type="submit">Install Coulobre</button></form>'
'<form method="post" action="/edit">' '<form method="post" action="/edit">'
'<button type="submit">Change settings</button></form>' '<button type="submit">Change settings</button></form>'
) )
else: else:
self.page( self.page(installation_form(state.form_values))
FORM.format(dns=role_form("dns"), mail=role_form("mail"))
)
def fields(self): def fields(self):
try: try:
@@ -305,6 +357,7 @@ class WizardHandler(BaseHTTPRequestHandler):
if self.path == "/edit": if self.path == "/edit":
state.pending = None state.pending = None
elif self.path == "/review": elif self.path == "/review":
state.form_values = data
state.pending = form_plan(data) state.pending = form_plan(data)
elif self.path == "/install" and state.pending is not None: elif self.path == "/install" and state.pending is not None:
state.thread = Thread(target=state.install) state.thread = Thread(target=state.install)
+23
View File
@@ -5,6 +5,7 @@ from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from deploy.panel_installer.cli import save_interactive_plan
from deploy.panel_installer.config import ( from deploy.panel_installer.config import (
InstallError, InstallError,
parse_plan, parse_plan,
@@ -23,6 +24,28 @@ ADMIN = {"username": "operator", "email": "ops@example.net"}
class InstallerParametersTests(unittest.TestCase): class InstallerParametersTests(unittest.TestCase):
def test_interactive_export_reuses_the_same_plan(self):
plan = parse_plan(
{
"panel": {"hostname": "panel.example.net", "access": "acme"},
"admin": ADMIN,
"dns": {"mode": "local"},
"mail": {
"mode": "local",
"host": "panel.example.net",
"tls": "acme",
},
}
)
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "panel.toml"
with patch(
"deploy.panel_installer.cli.prompt", return_value=str(path)
):
save_interactive_plan(plan, None)
self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
self.assertEqual(parse_plan(read_plan(path)), plan)
def test_browser_and_parameter_file_share_the_same_plan(self): def test_browser_and_parameter_file_share_the_same_plan(self):
with tempfile.TemporaryDirectory() as folder: with tempfile.TemporaryDirectory() as folder:
params = Path(folder) / "panel.toml" params = Path(folder) / "panel.toml"