Merge branch 'feature/updater' into feature/store-i18n

This commit is contained in:
kevinveenbirkenbach committed 2026-10-28 03:43:19 +01:00
commit 5c8c9670ba
52 files changed
+2107 -32

No files matched your search

@@ -7,9 +7,9 @@ import subprocess
import sys
import tempfile
import unittest
import unittest.mock as mock
from datetime import UTC, datetime
from pathlib import Path
from unittest import mock
from . import PROJECT_ROOT
@@ -1,3 +1,5 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
__all__ = ["PROJECT_ROOT"]
@@ -0,0 +1,5 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
__all__ = ["PROJECT_ROOT"]
@@ -0,0 +1,289 @@
import importlib.util
import unittest
from ansible.errors import AnsibleFilterError
from . import PROJECT_ROOT
ROOT = "/opt/compose/"
LAYOUT = (".env", "config", "services", "volumes")
KNOWN = [
f"web-app-{name}"
for name in (
"mailu",
"stalwart",
"baserow",
"discourse",
"handmade",
"partial",
"odd",
"dotenv",
"outer",
"inner",
"alpha",
"zeta",
)
] + ["svc-db-postgres", "svc-db-mariadb", "svc-prx-openresty", "web-svc-simpleicons"]
def _load_module():
path = (
PROJECT_ROOT
/ "roles"
/ "sys-svc-compose"
/ "filter_plugins"
/ "compose_decommission_plan.py"
)
spec = importlib.util.spec_from_file_location("compose_decommission_plan", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore[union-attr]
return module
def _entry(path, isdir=False, isreg=False):
return {"path": path, "isdir": isdir, "isreg": isreg, "islnk": False}
def _instance(name, skip=()):
base = f"/opt/compose/{name}"
entries = [_entry(base, isdir=True)]
entries += [_entry(f"{base}/{d}", isdir=True) for d in LAYOUT if d not in skip]
if "compose.yml" not in skip:
entries.append(_entry(f"{base}/compose.yml", isreg=True))
return entries
def _namesakes(instance, *lines):
return {
"ansible_loop_var": "compose_stale_candidate",
"compose_stale_candidate": instance,
"stdout_lines": list(lines),
}
class TestComposeDecommissionPlan(unittest.TestCase):
def setUp(self):
self.plan = _load_module().compose_decommission_plan
def test_the_instance_of_a_role_removed_from_the_host_is_stale(self):
entries = _instance("mailu") + _instance("stalwart")
self.assertEqual(
self.plan(entries, ROOT, ["web-app-stalwart"], KNOWN),
{"stale": ["/opt/compose/mailu"], "unmanaged": []},
)
def test_the_instances_of_active_shared_services_are_kept(self):
entries = (
_instance("postgres")
+ _instance("mariadb")
+ _instance("openresty")
+ _instance("simpleicons")
)
active = [
"svc-db-postgres",
"svc-db-mariadb",
"svc-prx-openresty",
"web-svc-simpleicons",
]
self.assertEqual(
self.plan(entries, ROOT, active, KNOWN), {"stale": [], "unmanaged": []}
)
def test_a_full_instance_of_no_known_role_is_unmanaged(self):
entries = _instance("nextcloud-old") + _instance("mailu.bak")
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN),
{
"stale": [],
"unmanaged": ["/opt/compose/mailu.bak", "/opt/compose/nextcloud-old"],
},
)
def test_a_directory_without_compose_file_is_unmanaged(self):
entries = _instance("handmade", skip=("compose.yml",))
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN),
{"stale": [], "unmanaged": ["/opt/compose/handmade"]},
)
def test_each_missing_layout_directory_makes_the_directory_unmanaged(self):
for missing in LAYOUT:
with self.subTest(missing=missing):
self.assertEqual(
self.plan(_instance("partial", skip=(missing,)), ROOT, [], KNOWN),
{"stale": [], "unmanaged": ["/opt/compose/partial"]},
)
def test_a_compose_file_that_is_a_directory_does_not_count(self):
entries = [
*_instance("odd", skip=("compose.yml",)),
_entry("/opt/compose/odd/compose.yml", isdir=True),
]
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN),
{"stale": [], "unmanaged": ["/opt/compose/odd"]},
)
def test_a_layout_entry_that_is_a_file_does_not_count(self):
entries = [
*_instance("dotenv", skip=(".env",)),
_entry("/opt/compose/dotenv/.env", isreg=True),
]
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN),
{"stale": [], "unmanaged": ["/opt/compose/dotenv"]},
)
def test_hidden_directories_are_ignored(self):
self.assertEqual(
self.plan(_instance(".trash"), ROOT, [], KNOWN),
{"stale": [], "unmanaged": []},
)
def test_symlinks_and_files_below_the_root_are_ignored(self):
entries = [
{
"path": "/opt/compose/linked",
"isdir": False,
"isreg": False,
"islnk": True,
},
_entry("/opt/compose/README", isreg=True),
]
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN), {"stale": [], "unmanaged": []}
)
def test_a_layout_found_deeper_does_not_make_an_instance(self):
entries = [_entry("/opt/compose/outer", isdir=True)] + [
dict(
entry,
path=entry["path"].replace("/opt/compose/", "/opt/compose/outer/"),
)
for entry in _instance("inner")[1:]
]
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN),
{"stale": [], "unmanaged": ["/opt/compose/outer"]},
)
def test_the_root_matches_with_and_without_trailing_slash(self):
for root in ("/opt/compose", "/opt/compose/"):
with self.subTest(root=root):
self.assertEqual(
self.plan(_instance("mailu"), root, [], KNOWN)["stale"],
["/opt/compose/mailu"],
)
def test_a_group_name_that_is_no_role_does_not_keep_a_stale_instance(self):
self.assertEqual(
self.plan(_instance("mailu"), ROOT, ["servers", "web-app-stalwart"], KNOWN)[
"stale"
],
["/opt/compose/mailu"],
)
def test_both_lists_come_back_sorted(self):
entries = (
_instance("mailu")
+ _instance("baserow")
+ _instance("zeta", skip=("compose.yml",))
+ _instance("alpha", skip=("compose.yml",))
)
self.assertEqual(
self.plan(entries, ROOT, [], KNOWN),
{
"stale": ["/opt/compose/baserow", "/opt/compose/mailu"],
"unmanaged": ["/opt/compose/alpha", "/opt/compose/zeta"],
},
)
def test_no_entries_yield_an_empty_plan(self):
self.assertEqual(
self.plan([], ROOT, ["web-app-stalwart"], KNOWN),
{"stale": [], "unmanaged": []},
)
def test_wrongly_typed_arguments_fail(self):
cases = (
("/opt/compose/mailu", ROOT, [], KNOWN),
([], ["/opt/compose/"], [], KNOWN),
([], ROOT, "web-app-mailu", KNOWN),
([], ROOT, [], "web-app-mailu"),
)
for args in cases:
with self.subTest(args=args), self.assertRaises(AnsibleFilterError):
self.plan(*args)
class TestComposeDecommissionConfirm(unittest.TestCase):
def setUp(self):
self.confirm = _load_module().compose_decommission_confirm
self.plan = {
"stale": ["/opt/compose/discourse", "/opt/compose/mailu"],
"unmanaged": ["/opt/compose/handmade"],
}
def test_instances_without_namesakes_stay_stale(self):
self.assertEqual(
self.confirm(
self.plan,
[
_namesakes("/opt/compose/discourse"),
_namesakes("/opt/compose/mailu"),
],
),
dict(self.plan, foreign=[]),
)
def test_a_namesake_of_the_own_project_keeps_the_instance_stale(self):
result = self.confirm(
self.plan,
[
_namesakes("/opt/compose/discourse"),
_namesakes("/opt/compose/mailu", "mailu mailu"),
],
)
self.assertEqual(
result["stale"], ["/opt/compose/discourse", "/opt/compose/mailu"]
)
def test_a_namesake_without_compose_project_holds_the_instance_back(self):
self.assertEqual(
self.confirm(
self.plan,
[
_namesakes("/opt/compose/discourse", "discourse "),
_namesakes("/opt/compose/mailu"),
],
),
{
"stale": ["/opt/compose/mailu"],
"unmanaged": ["/opt/compose/handmade"],
"foreign": ["/opt/compose/discourse"],
},
)
def test_a_namesake_of_another_project_holds_the_instance_back(self):
result = self.confirm(
self.plan,
[
_namesakes("/opt/compose/discourse"),
_namesakes("/opt/compose/mailu", "mailu mailu", "mailu stalwart"),
],
)
self.assertEqual(result["foreign"], ["/opt/compose/mailu"])
self.assertEqual(result["stale"], ["/opt/compose/discourse"])
def test_no_probe_results_change_nothing(self):
plan = {"stale": [], "unmanaged": []}
self.assertEqual(self.confirm(plan, []), dict(plan, foreign=[]))
def test_wrongly_typed_arguments_fail(self):
for args in (([], []), (self.plan, {})):
with self.subTest(args=args), self.assertRaises(AnsibleFilterError):
self.confirm(*args)
if __name__ == "__main__":
unittest.main()
@@ -9,9 +9,9 @@ import stat
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
from typing import TYPE_CHECKING
from unittest import mock
from ansible.module_utils.testing import patch_module_args
@@ -3,8 +3,8 @@ import io
import os
import sys
import unittest
import unittest.mock as mock
import urllib.parse
from unittest import mock
from . import PROJECT_ROOT
@@ -3,9 +3,9 @@ import json
import sys
import tempfile
import unittest
import unittest.mock as mock
import urllib.error
from pathlib import Path
from unittest import mock
from . import PROJECT_ROOT
@@ -0,0 +1,138 @@
from __future__ import annotations
import importlib.util
import sys
import unittest
from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape
from . import PROJECT_ROOT
OVERRIDES = ("rtp_port_range", "nat_1_1_mapping", "keep_private_host")
TARGET = "/usr/local/etc/janus/janus.jcfg"
LAUNCHER = (
"[program:janus]\n"
"command=janus --config=/usr/local/etc/janus/janus.jcfg --disable-colors"
" --log-stdout --full-trickle --debug-level 3\n"
)
def _load_module(rel_path: str, name: str):
path = PROJECT_ROOT / rel_path
spec = importlib.util.spec_from_file_location(name, str(path))
mod = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules[name] = mod
spec.loader.exec_module(mod)
return mod
MODULE = _load_module(
"roles/web-app-nextcloud/filter_plugins/nextcloud_janus.py", "nextcloud_janus"
)
def _rendered_template() -> str:
env = Environment(
loader=FileSystemLoader(
str(PROJECT_ROOT / "roles/web-app-nextcloud/templates")
),
undefined=StrictUndefined,
keep_trailing_newline=True,
autoescape=select_autoescape(default_for_string=False),
)
return env.get_template("janus.jcfg.j2").render(
NEXTCLOUD_HPB_MEDIA_PORT_START=61000,
NEXTCLOUD_HPB_MEDIA_PORT_END=61999,
NEXTCLOUD_HPB_MEDIA_PUBLIC_IP="203.0.113.7",
)
def _stock_like() -> str:
lines = ["/* a block comment the image ships", " over two lines */"]
for line in _rendered_template().splitlines():
if line.strip().split(" ", 1)[0] in OVERRIDES:
lines.append("\t#" + line.strip() + "\t\t# commented out upstream")
continue
lines.append("\t\t# a comment line the image ships")
lines.append(line.replace(" = ", " = ") + "\t// trailing remark")
return "\n".join(lines) + "\n"
def _drift(stock: str, launcher: str = LAUNCHER) -> list[str]:
return MODULE.janus_config_drift(
_rendered_template(), stock, OVERRIDES, launcher, TARGET
)
class TestJanusSettings(unittest.TestCase):
def test_comments_and_blank_lines_are_dropped(self):
content = "# head\n\ngeneral: {\n\tdebug_level = 4\t\t# level\n}\n"
self.assertEqual(
MODULE.janus_settings(content, []), ["general:{", "debug_level=4", "}"]
)
def test_block_comments_and_a_trailing_semicolon_are_dropped(self):
content = "/* head\n tail */\ndebug_level = 4; /* level */\n"
self.assertEqual(MODULE.janus_settings(content, []), ["debug_level=4"])
def test_a_hash_inside_a_quoted_value_is_kept(self):
content = 'log_prefix = "[janus] #1" # prefix\n'
self.assertEqual(
MODULE.janus_settings(content, []), ['log_prefix="[janus] #1"']
)
def test_named_overrides_are_left_out(self):
content = 'nat: {\n\tnat_1_1_mapping = "1.2.3.4"\n\tnice_debug = false\n}\n'
self.assertEqual(
MODULE.janus_settings(content, ["nat_1_1_mapping"]),
["nat:{", "nice_debug=false", "}"],
)
def test_the_template_sets_every_override_once(self):
keys = [
setting.split("=", 1)[0]
for setting in MODULE.janus_settings(_rendered_template(), [])
]
for override in OVERRIDES:
self.assertEqual(keys.count(override), 1, override)
class TestJanusConfigDrift(unittest.TestCase):
def test_a_stock_file_that_differs_only_in_comments_and_layout_passes(self):
self.assertEqual(_drift(_stock_like()), [])
def test_a_moved_plugin_folder_stops_the_deploy(self):
stock = _stock_like().replace(
'"/usr/local/lib/janus/plugins"', '"/usr/lib/janus/plugins"'
)
self.assertEqual(len(_drift(stock)), 1)
def test_an_upstream_value_for_a_masked_key_stops_the_deploy(self):
stock = _stock_like().replace("\t#rtp_port_range", "\trtp_port_range", 1)
self.assertEqual(len(_drift(stock)), 1)
def test_a_setting_upstream_added_stops_the_deploy(self):
stock = _stock_like().replace("nat: {", "nat: {\n\tice_tcp = true", 1)
self.assertEqual(len(_drift(stock)), 1)
def test_an_empty_read_stops_the_deploy(self):
self.assertEqual(len(_drift("")), 1)
def test_janus_reading_a_generated_config_stops_the_deploy(self):
launcher = LAUNCHER.replace(TARGET, "/conf/janus.jcfg")
self.assertEqual(
_drift(_stock_like(), launcher),
[f"Janus is not started with --config={TARGET}"],
)
def test_a_config_path_that_only_shares_the_prefix_stops_the_deploy(self):
launcher = LAUNCHER.replace(f"{TARGET} ", f"{TARGET}.generated ")
self.assertEqual(len(_drift(_stock_like(), launcher)), 1)
def test_a_launcher_without_janus_stops_the_deploy(self):
self.assertEqual(len(_drift(_stock_like(), "")), 1)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,283 @@
from __future__ import annotations
import itertools
import unittest
import unittest.mock as mock
from jinja2 import (
ChainableUndefined,
ChoiceLoader,
DictLoader,
Environment,
FileSystemLoader,
select_autoescape,
)
import plugins.lookup.container_ports as container_ports_lookup
from plugins.lookup.container_volumes import container_volumes
from utils.cache import _reset_cache_for_tests
from utils.cache.files import PROJECT_ROOT, read_text
from utils.cache.yaml import load_yaml_any
from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TEMPL_COMPOSE
ROLE = "roles/web-app-nextcloud"
TEMPLATE = f"{ROLE}/{ROLE_FILE_TEMPL_COMPOSE}"
PUBLIC_IP = "203.0.113.7"
SERVICES = load_yaml_any(str(PROJECT_ROOT / ROLE / ROLE_FILE_META_SERVICES))
LEGACY_BRIDGE_ONBOARD = """ talk:
<container-base>
<lookup container_healthcheck ('talk',)>
<lookup container_image ('web-app-nextcloud', 'talk')>
<lookup compose_only ('container_name', <NEXTCLOUD_HPB_CONTAINER>)>
init: true
ports:
- "203.0.113.7:3480:3480/tcp"
- "203.0.113.7:3480:3480/udp"
- "203.0.113.7:50000-59999:50000-59999/udp"
- "203.0.113.7:50000-59999:50000-59999/tcp"
expose:
- "8081"
<lookup container_networks ()>"""
LEGACY_BRIDGE = """ talk:
<container-base>
<lookup container_healthcheck ('talk',)>
<lookup container_image ('web-app-nextcloud', 'talk')>
<lookup compose_only ('container_name', <NEXTCLOUD_HPB_CONTAINER>)>
init: true
expose:
- "8081"
<lookup container_networks ()>"""
LEGACY_HOST = """ talk:
<container-base>
<lookup container_healthcheck ('talk',)>
<lookup container_image ('web-app-nextcloud', 'talk')>
<lookup compose_only ('container_name', <NEXTCLOUD_HPB_CONTAINER>)>
init: true
network_mode: host"""
DIRECT_MOUNT = (
" \n"
" configs:\n"
" - source: janus_conf\n"
" target: /usr/local/etc/janus/janus.jcfg"
)
DIRECT_PORT = ' - "203.0.113.7:61000-61999:61000-61999/udp"'
class _Marker(ChainableUndefined):
def __str__(self):
return f"<{self._undefined_name}>"
__repr__ = __str__
def _bool(value):
if isinstance(value, bool):
return value
if value is None or isinstance(value, ChainableUndefined):
return False
return str(value).strip().lower() in {"y", "yes", "true", "on", "1"}
def _render(
template_text: str, *, onboard: bool, direct: bool, mode: str, network: str
) -> str:
applications = {"web-app-nextcloud": {"services": SERVICES}}
env = Environment(
loader=ChoiceLoader(
[
DictLoader(
{
"roles/sys-svc-compose/templates/base.yml.j2": "services:\n",
"roles/sys-svc-container/templates/base.yml.j2": " <container-base>\n",
"roles/sys-svc-container/templates/deploy.yml.j2": " <container-deploy>\n",
"compose.yml.j2": template_text,
}
),
FileSystemLoader(str(PROJECT_ROOT)),
]
),
trim_blocks=True,
lstrip_blocks=True,
keep_trailing_newline=True,
undefined=_Marker,
autoescape=select_autoescape(default_for_string=False),
)
env.filters["bool"] = _bool
env.filters["path_join"] = lambda parts: "/".join(str(part) for part in parts)
variables = {
"application_id": "web-app-nextcloud",
"NEXTCLOUD_PROXY_SERVICE": "proxy",
"NEXTCLOUD_SERVICE": "nextcloud",
"NEXTCLOUD_CRON_SERVICE": "cron",
"DEPLOYMENT_MODE": mode,
"NEXTCLOUD_HPB_SIGNALING_ENABLED": True,
"NEXTCLOUD_HPB_SERVICE": "talk",
"NEXTCLOUD_HPB_SIGNALING_PORT": 8081,
"NEXTCLOUD_HPB_NETWORK_MODE": network,
"NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED": onboard,
"NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS": True,
"NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST": PUBLIC_IP,
"NEXTCLOUD_HPB_MEDIA_DIRECT": direct,
"NEXTCLOUD_HPB_MEDIA_PUBLIC_IP": PUBLIC_IP,
}
def render_jinja(expression):
return env.from_string(expression).render(variables)
class _Applications:
def run(self, terms, variables=None):
return [applications]
class _Loader:
def get(self, name, **kwargs):
return _Applications()
def lookup(name, *args, **kwargs):
if name == "config":
return {"services.talk.direct_media": direct}[args[1]]
if name == "container_ports":
with mock.patch.object(container_ports_lookup, "lookup_loader", _Loader()):
return container_ports_lookup.LookupModule().run(
list(args), variables=variables
)[0]
if name == "container_volumes":
block = container_volumes(
applications, "web-app-nextcloud", args[0], render_jinja=render_jinja
)
return "\n" + block if block else block
return f"<lookup {name} {args!r}>"
env.globals["lookup"] = lookup
return env.get_template("compose.yml.j2").render(variables)
def _talk_block(rendered: str) -> str:
lines = rendered.splitlines()
start = lines.index(" talk:")
end = next(
index
for index in range(start + 1, len(lines))
if lines[index].strip() and not lines[index].startswith(" ")
)
return "\n".join(lines[start:end]).rstrip()
def _cells(direct: bool):
for onboard, mode, network in itertools.product(
(True, False), ("compose", "swarm"), ("bridge", "host")
):
yield {"onboard": onboard, "direct": direct, "mode": mode, "network": network}
def _legacy(cell) -> str:
if cell["network"] == "host":
return LEGACY_HOST
return LEGACY_BRIDGE_ONBOARD if cell["onboard"] else LEGACY_BRIDGE
class TestTalkComposeBlock(unittest.TestCase):
def test_every_cell_without_direct_media_renders_the_legacy_block(self):
template = read_text(str(PROJECT_ROOT / TEMPLATE))
for cell in _cells(direct=False):
with self.subTest(**cell):
self.assertEqual(_talk_block(_render(template, **cell)), _legacy(cell))
def test_host_networking_ignores_direct_media(self):
template = read_text(str(PROJECT_ROOT / TEMPLATE))
for cell in _cells(direct=True):
if cell["network"] == "host":
with self.subTest(**cell):
self.assertEqual(
_talk_block(_render(template, **cell)), LEGACY_HOST
)
def test_direct_media_adds_only_the_janus_mount_and_the_udp_range(self):
template = read_text(str(PROJECT_ROOT / TEMPLATE))
for cell in _cells(direct=True):
if cell["network"] != "bridge":
continue
with self.subTest(**cell):
block = _talk_block(_render(template, **cell))
legacy = _legacy(cell)
expected = legacy.replace(
" init: true", " init: true\n" + DIRECT_MOUNT
)
if cell["onboard"]:
expected = expected.replace(
" expose:", DIRECT_PORT + "\n expose:"
)
else:
expected = expected.replace(
" expose:", " ports:\n" + DIRECT_PORT + "\n expose:"
)
self.assertEqual(block, expected)
def test_negative_control_an_unguarded_mount_breaks_the_legacy_block(self):
template = read_text(str(PROJECT_ROOT / TEMPLATE)).replace(
" {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n"
" {{ lookup('container_volumes', service_name) | indent(4) }}\n",
" {{ lookup('container_volumes', service_name) | indent(4) }}\n"
" {% if NEXTCLOUD_HPB_MEDIA_DIRECT | bool %}\n",
)
cell = {
"onboard": False,
"direct": False,
"mode": "compose",
"network": "bridge",
}
rendered = _render(template, **cell)
self.assertNotIn("janus_conf", rendered)
self.assertNotEqual(_talk_block(rendered), _legacy(cell))
def _direct_media(group_names, *, mode="compose", ip4=PUBLIC_IP, applications=None):
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from utils.cache.applications import get_merged_applications
variables = {
"group_names": group_names,
"applications": applications or {},
"DEPLOYMENT_MODE": mode,
"networks": {"internet": {"ip4": ip4, "ip6": "::1"}},
"ansible_facts": {"all_ipv4_addresses": [PUBLIC_IP, "10.208.0.1"]},
}
templar = Templar(loader=DataLoader(), variables=dict(variables))
templar.available_variables = dict(variables)
_reset_cache_for_tests()
try:
merged = get_merged_applications(variables=variables, templar=templar)
finally:
_reset_cache_for_tests()
return merged["web-app-nextcloud"]["services"]["talk"]["direct_media"]
STANDALONE_TURN = ("web-app-nextcloud", "web-svc-coturn")
class TestDirectMediaFlag(unittest.TestCase):
def test_compose_with_standalone_turn_and_an_owned_address_turns_it_on(self):
self.assertIs(_direct_media(list(STANDALONE_TURN)), True)
def test_an_address_the_host_does_not_own_keeps_it_off(self):
self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="198.51.100.9"), False)
def test_the_loopback_placeholder_keeps_it_off(self):
self.assertIs(_direct_media(list(STANDALONE_TURN), ip4="127.0.0.1"), False)
def test_swarm_keeps_it_off(self):
self.assertIs(_direct_media(list(STANDALONE_TURN), mode="swarm"), False)
def test_onboard_turn_keeps_it_off(self):
forced = {"web-app-nextcloud": {"services": {"talk": {"enabled": True}}}}
self.assertIs(_direct_media(["web-app-nextcloud"], applications=forced), False)
if __name__ == "__main__":
unittest.main()
Whitespace-only changes.
@@ -0,0 +1,5 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
__all__ = ["PROJECT_ROOT"]
@@ -0,0 +1,213 @@
"""coturn pins its addresses only on host networking in compose mode, and only addresses the host owns.
Pinned, coturn listens on ``networks.internet.ip4``, on loopback for the
healthcheck and on ``networks.internet.ip6``, and relays on
``networks.internet.ip4`` instead of on whichever Docker bridge address the
allocation happens to land on. coturn exits when it cannot bind a listening
address, and a pinned coturn stops answering on every address it was not
given. So the command is pinned only when the host carries ip4 and either
carries ip6 as written or ip6 is unset (empty or the ``defaults_networks``
placeholder); any other host keeps the unpinned command the role rendered
before, instead of losing its IPv6 listener or failing to bind.
The real ``vars/main.yml`` is resolved by Ansible's templar and the real
``compose.yml.j2`` is rendered with the role's lookups stubbed, so a broken
ownership check or a gate that leaks into bridge or swarm mode fails here.
"""
from __future__ import annotations
import re
import unittest
from ansible.parsing.dataloader import DataLoader
from ansible.plugins.filter.core import to_bool
from ansible.template import Templar
from jinja2 import DictLoader, Environment, StrictUndefined, select_autoescape
from utils.cache.files import read_text
from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE, ROLE_FILE_VARS_MAIN
from . import PROJECT_ROOT
ROLE = PROJECT_ROOT / "roles/web-svc-coturn"
TEMPLATE = ROLE / ROLE_FILE_TEMPL_COMPOSE
VARS = ROLE / ROLE_FILE_VARS_MAIN
NETWORK_DEFAULTS = DataLoader().load_from_file(
str(PROJECT_ROOT / "group_vars/all/08_networks.yml")
)["defaults_networks"]
PLACEHOLDER_IP6 = NETWORK_DEFAULTS["internet"]["ip6"]
IP4 = "198.51.100.7"
IP6 = "2001:db8:1::2"
FOREIGN_IP4 = "203.0.113.7"
FOREIGN_IP6 = "2001:db8:ffff::9"
LOOPBACK = "127.0.0.1"
OWNED = {
"all_ipv4_addresses": [IP4, "172.17.0.1", "192.168.101.1"],
"all_ipv6_addresses": [IP6, "fe80::1"],
}
RESOLVED = (
"COTURN_LOOPBACK_IP",
"COTURN_RELAY_IP",
"COTURN_ADDRESSES_PINNED",
"COTURN_LISTENING_IPS",
)
STUBBED = {
"application_id": "web-svc-coturn",
"entity_name": "coturn",
"COTURN_CONTAINER": "coturn",
"COTURN_USER_AUTH_ENABLED": False,
"COTURN_TOTAL_QUOTA": 2000,
"COTURN_STUN_TURN_PORT": 3481,
"COTURN_STUN_TURN_PORT_TLS": 5351,
"COTURN_RELAY_PORT_START": 20000,
"COTURN_RELAY_PORT_END": 39999,
"COTURN_TLS_ENABLED": True,
"COTURN_TLS_CERT_PATH": "/etc/coturn/cert.pem",
"COTURN_TLS_KEY_PATH": "/etc/coturn/key.pem",
"DOCKER_BIND_HOST": LOOPBACK,
}
INCLUDES = {
"roles/sys-svc-compose/templates/base.yml.j2": "services:\n",
"roles/sys-svc-container/templates/base.yml.j2": "",
}
_HEALTHCHECK = re.compile(r"turnutils_stunclient -p \d+ (\S+) \|\| nc -z (\S+) \d+")
def render(
*,
ip4: str = IP4,
ip6: str = IP6,
facts: dict | None = None,
mode: str = "compose",
network: str = "host",
) -> str:
"""The coturn compose file for one deployment.
Args:
ip4: ``networks.internet.ip4``.
ip6: ``networks.internet.ip6``.
facts: the host's ``ansible_facts``; ``None`` means a host owning ``OWNED``.
mode: ``DEPLOYMENT_MODE``.
network: ``services.coturn.network_mode``.
"""
inputs = {
"networks": {"internet": {"ip4": ip4, "ip6": ip6, "dns": ""}},
"defaults_networks": NETWORK_DEFAULTS,
"ansible_facts": OWNED if facts is None else facts,
"DEPLOYMENT_MODE": mode,
"COTURN_NETWORK_MODE": network,
}
declared = DataLoader().load_from_file(str(VARS), trusted_as_template=True)
templar = Templar(loader=DataLoader(), variables={**declared, **inputs})
values = {name: templar.template(declared[name]) for name in RESOLVED}
env = Environment(
autoescape=select_autoescape(default_for_string=False),
undefined=StrictUndefined,
trim_blocks=True,
lstrip_blocks=True,
loader=DictLoader(INCLUDES),
)
env.filters["bool"] = to_bool
env.globals["lookup"] = lambda *_args, **_kwargs: ""
return env.from_string(read_text(str(TEMPLATE))).render(
**STUBBED, **inputs, **values
)
def listening(rendered: str) -> list[str]:
return re.findall(r"--listening-ip=(\S+)", rendered)
def relay(rendered: str) -> list[str]:
return re.findall(r"--relay-ip=(\S+)", rendered)
class TestOwnedAddressesArePinned(unittest.TestCase):
def test_listeners_cover_ip4_loopback_and_ip6(self) -> None:
self.assertEqual(listening(render()), [IP4, LOOPBACK, IP6])
def test_relays_stay_on_ip4(self) -> None:
self.assertEqual(
relay(render()),
[IP4],
"without the pin coturn may place a relay on a Docker bridge "
"address and still announce the external IP for it",
)
def test_the_healthcheck_probes_a_pinned_listener(self) -> None:
rendered = render()
probed = _HEALTHCHECK.search(rendered)
self.assertIsNotNone(probed, "the healthcheck command changed shape")
for address in probed.groups():
self.assertIn(
address,
listening(rendered),
"a pinned coturn answers only on its listening addresses, so a "
"probe aimed elsewhere marks a healthy server unhealthy",
)
class TestAnUnsetIpv6IsLeftOut(unittest.TestCase):
def test_the_placeholder_is_left_out(self) -> None:
rendered = render(ip6=PLACEHOLDER_IP6)
self.assertEqual(
(listening(rendered), relay(rendered)), ([IP4, LOOPBACK], [IP4])
)
def test_an_empty_ipv6_is_left_out(self) -> None:
rendered = render(ip6="")
self.assertEqual(
(listening(rendered), relay(rendered)), ([IP4, LOOPBACK], [IP4])
)
class TestAddressesTheHostLacksKeepTheUnpinnedCommand(unittest.TestCase):
def test_a_foreign_ipv6(self) -> None:
rendered = render(ip6=FOREIGN_IP6)
self.assertEqual(
(listening(rendered), relay(rendered)),
([], []),
"pinning ip4 alone would drop the IPv6 listener the unpinned "
"command still had",
)
def test_an_ipv6_written_unlike_the_interface_lists_it(self) -> None:
rendered = render(ip6=IP6.upper())
self.assertEqual((listening(rendered), relay(rendered)), ([], []))
def test_a_foreign_ipv4_keeps_the_unpinned_command(self) -> None:
rendered = render(ip4=FOREIGN_IP4)
self.assertEqual(
(listening(rendered), relay(rendered)),
([], []),
"a 1:1-NAT host carries its public IPv4 nowhere, so pinning it "
"stops coturn from binding at all",
)
def test_a_host_without_address_facts_keeps_the_unpinned_command(self) -> None:
rendered = render(facts={})
self.assertEqual((listening(rendered), relay(rendered)), ([], []))
class TestOtherModesAreUnchanged(unittest.TestCase):
def test_bridge_and_swarm_never_pin(self) -> None:
for mode, network in (
("compose", "bridge"),
("swarm", "host"),
("swarm", "bridge"),
):
with self.subTest(mode=mode, network=network):
rendered = render(mode=mode, network=network)
self.assertEqual((listening(rendered), relay(rendered)), ([], []))
if __name__ == "__main__":
unittest.main()