"""Collect a cluster inventory for the automated installer.""" from . import guidance from .cluster import SCOPE, ClusterInstaller, parse_cluster from .config import ( InstallError, admin_email, comma_separated, file_path, hostname, read_password, read_smtp_password, smtp_credential, ) from .interactive import ( InteractiveSetup, ask_checked, local_path, typed_port, validated_list, ) from .terminal import PreviousStepError def panel_name(value): if not SCOPE.fullmatch(value): raise InstallError("Use 1 to 12 lowercase letters, digits or hyphens.") return value def count(value): if value not in {str(number) for number in range(2, 13)}: raise InstallError("Enter a panel count from 2 to 12.") return int(value) def collect_receiver(terminal, name, previous, defaults=None): terminal.heading(f"Shared {name.upper()} receiver") selected = terminal.choose( "Configure a shared receiver", ("yes", "no"), "yes" if previous else "no", hint="Enter a dedicated host. DNS and mail can share the same host.", ) if selected == "no": return {} setup = InteractiveSetup(terminal) setup.data = { name: previous | {"mode": "remote-install"}, "panel": {"access": "acme"}, } setup.answers.update( ((name, field), value) for field, value in ((defaults or {}) | previous).items() ) setup.role_settings(name) result = setup.data[name] result.pop("mode") if name == "mail": def sending(value): addresses = validated_list("mail_sending_addresses", value) if not addresses: raise InstallError( "Enter at least one public sending address." ) return addresses result["sending_addresses"] = ask_checked( terminal, "Public SMTP sending IPs", ", ".join(previous.get("sending_addresses", ())), sending, hint=guidance.HOSTING_FIELDS[-1][2], ) return result def collect_panel(terminal, index, previous, receivers, defaults=None): initial = defaults or {} if previous: initial = previous terminal.heading( "Local panel" if index == 0 else f"Remote panel {index + 1}" ) name = ask_checked( terminal, "Panel identifier", previous.get("name", f"srv{index + 1}"), panel_name, hint="Use a stable name for this panel's receiver access.", ) setup = InteractiveSetup(terminal) setup.data = { key: initial[key] for key in ("panel", "admin") if key in initial } for section in ("panel", "admin"): setup.answers.update( ((section, key), value) for key, value in initial.get(section, {}).items() ) if transport := initial.get("ssh"): setup.answers.update( ((name, key), value) for key, value in transport.items() ) stages = [] connection = {} if index: def ssh_settings(): terminal.heading("SSH connection") connection.update(setup.ssh_settings(name, "remote-install")) stages.append(ssh_settings) hosting = {} stages.extend( ( lambda: setup.panel(remote=bool(index)), setup.admin, lambda: hosting.update( collect_hosting(terminal, name, hosting or initial, receivers) ), ) ) context = terminal.context for_sections( terminal, stages, f"{context} / {name}", back=terminal.can_go_back ) return { "name": name, "panel": setup.data["panel"], "admin": setup.data["admin"], **hosting, **({"ssh": connection} if connection else {}), } def collect_hosting(terminal, name, previous, receivers): terminal.heading(f"Hosting on {name}") dns = terminal.choose( "DNS on this panel", ("shared", "local", "off") if "dns" in receivers else ("local", "off"), previous.get("dns") if previous.get("dns") in {"local", "off"} or ("dns" in receivers and previous.get("dns") == "shared") else ("shared" if "dns" in receivers else "local"), hint=guidance.DNS_ROLE if "dns" not in receivers else "Shared DNS publishes zones on the receiver.", ) hosting = {} for field, label, hint in guidance.HOSTING_FIELDS[:2]: if field == "nameservers" and dns == "off": continue hosting[field] = ask_checked( terminal, label, ", ".join(previous.get("hosting", {}).get(field, ())) or "none", lambda value, field=field: validated_list(field, value), hint=hint, ) result = {"hosting": hosting, "dns": dns} if "mail" in receivers or dns == "shared": result["domains"] = ask_checked( terminal, "Assigned hosted domains", ", ".join(previous.get("domains", ())) or "none", assigned_domains, hint=( "Enter comma-separated domains or choose none to reserve " "receiver access without permitting domain changes." ), ) if relay := collect_smtp(terminal, previous.get("smtp"), receivers): result["smtp"] = relay return result def collect_smtp(terminal, previous, receivers): if ( terminal.choose( "Outgoing panel email", ("later", "smtp"), "smtp" if previous else "later", hint="Used for welcome email and account security. A shared " "mail receiver does not create an SMTP login for the panel.", ) == "later" ): return {} previous = previous or {} mail = receivers.get("mail", {}) def private_path(value): path = local_path(value) read_smtp_password(path) return path return { "host": ask_checked( terminal, "SMTP hostname", previous.get("host") or mail.get("mail_hostname", ""), lambda value: hostname(value, "SMTP"), ), "port": ask_checked( terminal, "SMTP STARTTLS port", str(previous.get("port", 587)), lambda value: typed_port(value, "SMTP", 587), ), "username": ask_checked( terminal, "SMTP username", previous.get("username", ""), smtp_credential, ), "sender": ask_checked( terminal, "Panel From address", previous.get("sender", ""), admin_email, ), "password_file": ask_checked( terminal, "Private SMTP password file", previous.get("password_file", ""), private_path, hint="Use an absolute path to a private file on this machine.", ), } def shared_ssh_defaults(connection): return { field: connection[field] for field in ("port", "ssh_user", "ssh_identity") if field in connection } def panel_defaults(draft, index): earlier = [panel for panel in draft["panels"][:index] if panel] if not earlier: return {} previous = earlier[-1] transport = ( previous.get("ssh") or draft.get("mail") or draft.get("dns", {}) ) hosting = previous.get("hosting", {}) return { "panel": {"access": previous["panel"]["access"]}, "admin": { field: previous["admin"][field] for field in ("username", "email") if field in previous["admin"] }, "dns": previous["dns"], "hosting": {"nameservers": hosting.get("nameservers", [])}, "ssh": shared_ssh_defaults(transport), } def for_sections(terminal, sections, title, *, back=False): previous_context, previous_back = terminal.context, terminal.can_go_back index = 0 try: while index < len(sections): terminal.context = f"{title} / {index + 1} of {len(sections)}" terminal.can_go_back = index > 0 or back try: sections[index]() except PreviousStepError: if index == 0: raise index -= 1 else: index += 1 finally: terminal.context, terminal.can_go_back = ( previous_context, previous_back, ) def assigned_domains(value): if value.lower() == "none": return [] domains = [ hostname(item, "hosted domain") for item in comma_separated(value) ] if not 1 <= len(domains) <= 200: raise InstallError("Enter up to 200 hosted domains or none.") return domains def edit_inventory(terminal, draft): terminal.context = "Cluster review" terminal.heading("Edit cluster") changed = terminal.choose( "Section", ("dns", "mail", "panels", "back"), "back" ) if changed in {"dns", "mail"}: receiver = collect_receiver(terminal, changed, draft.get(changed, {})) if receiver: draft[changed] = receiver else: draft.pop(changed, None) if not receiver and changed == "dns": for entry in draft["panels"]: if entry["dns"] == "shared": entry["dns"] = "local" for panel in draft["panels"]: if ("mail" in draft or panel["dns"] == "shared") and not panel.get( "domains" ): terminal.heading(f"Receiver access for {panel['name']}") panel["domains"] = ask_checked( terminal, "Assigned hosted domains", "none", assigned_domains, ) elif changed == "panels": choices = tuple( str(index) for index in range(1, len(draft["panels"]) + 1) ) for prompt, entry in zip(choices, draft["panels"], strict=True): terminal.show( f"{prompt}. {entry['name']} ({entry['panel']['hostname']})" ) panel = terminal.choose("Panel", (*choices, "back"), "back") if panel != "back": index = int(panel) - 1 terminal.context = f"Cluster / Panel {index + 1} of {len(choices)}" draft["panels"][index] = collect_panel( terminal, index, draft["panels"][index], draft ) def collect_inventory(terminal): terminal.step = None terminal.context = "Cluster / Topology" terminal.heading("Cluster topology") terminal.show( "Start on the first panel server. Provide SSH access from this server " "to the other panels and any shared receivers." ) size = ask_checked(terminal, "Number of panel servers", 3, count) draft = {"panels": [{} for _ in range(size)]} def receiver_section(name): terminal.context = f"{terminal.context} / Shared {name.upper()}" defaults = shared_ssh_defaults(draft.get("dns", {})) receiver = collect_receiver( terminal, name, draft.get(name, {}), defaults ) if receiver: draft[name] = receiver else: draft.pop(name, None) def panel_section(index): terminal.context = f"Cluster / Panel {index + 1} of {size}" draft["panels"][index] = collect_panel( terminal, index, draft["panels"][index], draft, panel_defaults(draft, index), ) for_sections( terminal, ( lambda: receiver_section("dns"), lambda: receiver_section("mail"), *( lambda index=index: panel_section(index) for index in range(size) ), ), "Cluster configuration", ) return draft def collect_cluster(terminal): draft = collect_inventory(terminal) data = {"cluster": draft} checked = False while True: terminal.context = "Cluster / Review and preflight" terminal.heading("Review cluster") try: cluster = parse_cluster(data) except InstallError as error: terminal.error(error) choices = ("edit", "cancel") else: for item in cluster.summary(): terminal.show(item) terminal.show( "Preflight passed for all destinations." if checked else "Check connections to test SSH, sudo and destination " "settings before starting installation." ) choices = ( ("install", "check connections", "edit", "cancel") if checked else ("check connections", "edit", "cancel") ) chosen = terminal.choose("Next step", choices, "cancel") if chosen == "cancel": return None if chosen == "install": return cluster, data while chosen == "check connections": checked = False terminal.heading("Checking cluster destinations") try: ClusterInstaller( cluster, dict.fromkeys((p.name for p in cluster.panels), ""), terminal.status, ).check() except (InstallError, OSError, ValueError) as error: terminal.error(error) chosen = terminal.choose( "Cluster check failed", ("edit", "retry", "review", "cancel"), "edit", ) if chosen == "retry": chosen = "check connections" else: checked = True chosen = "review" if chosen == "cancel": return None if chosen == "edit": checked = False edit_inventory(terminal, draft) def collect_password(terminal, entry, *, default="", masked_password): terminal.heading(f"Administrator for {entry['name']}") candidate = terminal.prompt( "Administrator password file", default, hint=( "Use a root-owned 0600 file on this server or leave blank " "to type the password." ), ) while candidate: try: path = file_path( local_path(candidate), "the administrator password file" ) password = read_password(path) except InstallError as error: terminal.error(error) candidate = terminal.prompt("Administrator password file") else: entry["admin"]["password_file"] = path return password return masked_password(terminal)