Files
coulobre/tests/test_cluster_installer.py
T

246 lines
9.3 KiB
Python
Raw Normal View History

import json
import tempfile
import tomllib
import unittest
from contextlib import nullcontext, redirect_stdout
from io import StringIO
from pathlib import Path
from unittest.mock import Mock, patch
from deploy.panel_installer import cluster
from deploy.panel_installer.cli import (
interactive_configuration,
main,
write_interactive_plan,
)
from deploy.panel_installer.config import InstallError, parse_plan
from deploy.panel_installer.terminal import PlainTerminal
class ClusterInstallerTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.folder = Path(directory.name)
self.pin = self.folder / "host.pub"
self.pin.write_text("ssh-ed25519 fixture-public-key\n")
self.config = {
"cluster": {
"mail": self.connection("192.0.2.24")
| {
"mail_hostname": "mail.example.net",
"tls": "acme",
"sending_addresses": ["93.184.215.14"],
},
"panels": [
self.panel("one"),
self.panel("two") | {"ssh": self.connection("192.0.2.22")},
self.panel("three")
| {"ssh": self.connection("192.0.2.23")},
],
}
}
def connection(self, host):
return {
"host": host,
"host_key": str(self.pin),
"ssh_user": "root",
"ssh_identity": "/root/cluster-admin",
}
def panel(self, name):
return {
"name": name,
"panel": {"hostname": f"{name}.example.net", "access": "acme"},
"admin": {
"email": "ops@example.net",
"password_file": f"/root/{name}-password",
},
"domains": [],
}
def test_cluster_toml_round_trip_preserves_panel_and_receiver_settings(
self,
):
path = self.folder / "cluster.toml"
write_interactive_plan(path, self.config, None, replace=False)
stored = tomllib.loads(path.read_text())
self.assertEqual(stored, self.config)
topology = cluster.parse_cluster(stored)
self.assertEqual(
[p.plan.hostname for p in topology.panels],
["one.example.net", "two.example.net", "three.example.net"],
)
panel = topology.panels[1]
self.assertEqual(panel.scopes, {"mail": "two"})
self.assertEqual(panel.plan.mail.mode, "remote")
self.assertEqual(panel.plan.mail.mail_hostname, "mail.example.net")
self.assertEqual(
panel.plan.hosting.mail_sending_addresses, ("93.184.215.14",)
)
self.assertEqual(panel.domains, [])
def test_rejects_overlapping_domains_on_shared_dns(self):
self.config["cluster"]["dns"] = self.connection("192.0.2.24")
first, second, _ = self.config["cluster"]["panels"]
first["domains"] = ["example.net"]
second["domains"] = ["customer.example.net"]
with self.assertRaisesRegex(InstallError, "single|one panel"):
cluster.parse_cluster(self.config)
def test_hydrates_remote_plan_using_only_public_receiver_keys(self):
topology = cluster.parse_cluster(self.config)
panel = topology.panels[1]
payload = {"plan": panel.parameters, "pins": panel.pins}
self.assertEqual(cluster.parse_remote_panel(payload), panel.plan)
self.assertNotIn("ssh_identity", payload["plan"]["mail"])
def test_checks_all_destinations_before_changes_and_resumes_failed_panel(
self,
):
topology = cluster.parse_cluster(self.config)
local = Mock(plan=topology.panels[0].plan, release="1.0.0rc1")
local.prepare_cluster_keys.return_value = {"mail": "public-one"}
events = []
fail_third = True
machines = {"192.0.2.22": "2", "192.0.2.23": "3", "192.0.2.24": "4"}
def request(target, settings, *, result=False):
action = settings["role"]
events.append((action, target.host))
if action == "cluster-check":
return {"machine": machines[target.host] * 32}
if action == "cluster-keys":
return {"mail": f"public-{target.host}"}
if action == "mail":
self.assertEqual(settings["domains"], [])
self.assertIn(settings["scope"], {"one", "two", "three"})
self.assertNotIn("password", settings)
if action == "cluster-panel":
self.assertNotIn("ssh_identity", settings)
if target.host == "192.0.2.23" and fail_third:
raise InstallError("Installation interrupted.")
def state_file(path, payload, **kwargs):
path.write_text(payload)
with (
patch.object(cluster, "STATE", self.folder),
patch.object(cluster, "cluster_lock", return_value=nullcontext()),
patch.object(cluster, "preserve_pins"),
patch.object(cluster, "cluster_request", side_effect=request),
patch.object(cluster.remote, "check_panel_destination"),
patch.object(cluster.engine, "Installer", return_value=local),
patch.object(cluster.engine, "root_file"),
patch.object(cluster.engine, "put_file", side_effect=state_file),
):
installer = cluster.ClusterInstaller(
topology,
dict.fromkeys(("one", "two", "three"), "fixture"),
Mock(),
)
with self.assertRaisesRegex(InstallError, "interrupted"):
installer.install()
self.assertEqual(
events[:3],
[("cluster-check", endpoint) for endpoint in machines],
)
self.assertEqual(
json.loads((self.folder / "installation.json").read_text())[
"complete"
],
["one", "two"],
)
fail_third = False
events.clear()
installer.install()
self.assertIn(("cluster-panel", "192.0.2.23"), events)
self.assertNotIn(("cluster-panel", "192.0.2.22"), events)
local.install.assert_called_once()
self.assertEqual(
json.loads((self.folder / "installation.json").read_text())[
"complete"
],
["one", "two", "three"],
)
def test_refuses_two_endpoints_with_the_same_machine_identity(self):
topology = cluster.parse_cluster(self.config)
local = Mock(plan=topology.panels[0].plan, release="1.0.0rc1")
with (
patch.object(
cluster, "cluster_request", return_value={"machine": "2" * 32}
),
patch.object(cluster.remote, "check_panel_destination"),
patch.object(cluster.engine, "Installer", return_value=local),
):
installer = cluster.ClusterInstaller(
topology,
dict.fromkeys(("one", "two", "three"), "fixture"),
Mock(),
)
with self.assertRaisesRegex(InstallError, "distinct machine ID"):
installer.check()
local.install.assert_not_called()
def test_automated_check_does_not_open_the_terminal_or_install(self):
path = self.folder / "cluster.toml"
write_interactive_plan(path, self.config, None, replace=False)
with (
patch("deploy.panel_installer.cli.platform_settings"),
patch.object(cluster, "read_password", return_value="fixture"),
patch("deploy.panel_installer.cli.ClusterInstaller") as installer,
patch("deploy.panel_installer.cli.configure_terminal") as terminal,
redirect_stdout(StringIO()),
):
self.assertEqual(main(["--config", str(path), "--check"]), 0)
installer.return_value.check.assert_called_once()
installer.return_value.install.assert_not_called()
terminal.assert_not_called()
def test_single_plan_rejects_cluster_inventory(self):
with self.assertRaises(InstallError):
parse_plan(self.config)
def test_cluster_is_a_topology_in_the_interactive_entry_point(self):
inputs = [
"cluster",
"2",
"no",
"no",
"one",
"one.example.net",
"",
"",
"ops@example.net",
"",
"",
"",
"two",
"192.0.2.22",
"",
str(self.pin),
"root",
"/root/ssh-key",
"two.example.net",
"",
"",
"ops@example.net",
"",
"",
"",
"cancel",
]
output = StringIO()
with (
patch("builtins.input", side_effect=inputs),
patch("deploy.panel_installer.interactive.root_file"),
redirect_stdout(output),
):
self.assertIsNone(interactive_configuration(PlainTerminal(), None))
self.assertIn("=== Review cluster ===", output.getvalue())
self.assertIn("one.example.net (this server)", output.getvalue())
self.assertIn(
"two.example.net (SSH 192.0.2.22:22)", output.getvalue()
)