Files

287 lines
13 KiB
Python

# Copyright 2024-2025 New Vector Ltd
# Copyright 2025-2026 Element Creations Ltd
#
# SPDX-License-Identifier: AGPL-3.0-only
import random
import string
import pyhelm3
import pytest
import yaml
from . import DeployableDetails, PropertyType
from .utils import (
PERSISTENT_WORKLOAD_KINDS,
iterate_deployables_ingress_parts,
iterate_deployables_parts,
iterate_pod_template,
)
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_appservice_configmaps_are_templated(release_name, values, make_templates):
values["synapse"].setdefault("appservices", []).append(
{"configMap": "as-{{ $.Release.Name }}", "configMapKey": "reg.yaml"}
)
for template in await make_templates(values):
if (
template["metadata"]["name"].startswith(f"{release_name}-synapse")
and template["kind"] in PERSISTENT_WORKLOAD_KINDS
):
for volume in template["spec"]["template"]["spec"]["volumes"]:
if (
"configMap" in volume
and volume["configMap"]["name"] == f"as-{release_name}"
and volume["name"] == "as-0"
):
break
else:
raise AssertionError(
"The appservice configMap wasn't included in the volumes : "
f"{','.join([volume['name'] for volume in template['spec']['template']['spec']['volumes']])}"
)
for volumeMount in template["spec"]["template"]["spec"]["containers"][0]["volumeMounts"]:
if volumeMount["name"] == "as-0" and volumeMount["mountPath"] == "/as/0/reg.yaml":
break
else:
raise AssertionError("The appservice configMap isn't mounted at the expected location")
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_appservice_secrets_are_templated(release_name, values, make_templates):
values["synapse"].setdefault("appservices", []).append(
{"secret": "as-{{ $.Release.Name }}", "secretKey": "reg.yaml"}
)
for template in await make_templates(values):
if (
template["metadata"]["name"].startswith(f"{release_name}-synapse")
and template["kind"] in PERSISTENT_WORKLOAD_KINDS
):
for volume in template["spec"]["template"]["spec"]["volumes"]:
if (
"secret" in volume
and volume["secret"]["secretName"] == f"as-{release_name}"
and volume["name"] == "as-0"
):
break
else:
raise AssertionError(
"The appservice secret wasn't included in the volumes : "
f"{','.join([volume['name'] for volume in template['spec']['template']['spec']['volumes']])}"
)
for volumeMount in template["spec"]["template"]["spec"]["containers"][0]["volumeMounts"]:
if volumeMount["name"] == "as-0" and volumeMount["mountPath"] == "/as/0/reg.yaml":
break
else:
raise AssertionError("The appservice secret isn't mounted at the expected location")
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_max_upload_size_annotation_global_ingressType(values, make_templates):
for template in await make_templates(values):
if template["kind"] == "Ingress":
assert "nginx.ingress.kubernetes.io/proxy-body-size" not in template["metadata"].get("annotations", {})
values.setdefault("ingress", {})["controllerType"] = "ingress-nginx"
for template in await make_templates(values):
if template["kind"] == "Ingress":
assert "nginx.ingress.kubernetes.io/proxy-body-size" in template["metadata"].get("annotations", {})
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_max_upload_size_annotation_component_ingressType(values, make_templates):
def set_ingress_type(deployable_details: DeployableDetails):
deployable_details.set_helm_values(values, PropertyType.Ingress, {"controllerType": "ingress-nginx"})
for template in await make_templates(values):
if template["kind"] == "Ingress":
assert "nginx.ingress.kubernetes.io/proxy-body-size" not in template["metadata"].get("annotations", {})
iterate_deployables_ingress_parts(set_ingress_type)
for template in await make_templates(values):
if template["kind"] == "Ingress":
assert "nginx.ingress.kubernetes.io/proxy-body-size" in template["metadata"].get("annotations", {})
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_log_level_overrides(values, make_templates):
for template in await make_templates(values):
if (
template["kind"] == "ConfigMap"
and "synapse" in template["metadata"]["name"]
and "log_config.yaml" in template["data"]
):
log_yaml = yaml.safe_load(template["data"]["log_config.yaml"])
log_level = log_yaml["root"]["level"]
loggers = log_yaml["loggers"]
assert log_level == "INFO"
assert loggers == {
"synapse.storage.SQL": {"level": "INFO"},
}
break
else:
raise RuntimeError("Could not find log_config.yaml")
values["synapse"]["logging"] = {
"rootLevel": "WARNING",
"levelOverrides": {"synapse.storage.SQL": "DEBUG", "synapse.over.value": "INFO"},
}
for template in await make_templates(values):
if (
template["kind"] == "ConfigMap"
and "synapse" in template["metadata"]["name"]
and "log_config.yaml" in template["data"]
):
log_yaml = yaml.safe_load(template["data"]["log_config.yaml"])
log_level = log_yaml["root"]["level"]
loggers = log_yaml["loggers"]
assert log_level == "WARNING"
assert loggers == {"synapse.storage.SQL": {"level": "DEBUG"}, "synapse.over.value": {"level": "INFO"}}
break
else:
raise RuntimeError("Could not find log_config.yaml")
@pytest.mark.parametrize("values_file", ["synapse-worker-example-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_synapse_resources_shared_by_default(values, make_templates):
resources = {
"requests": {
"cpu": "1000",
"memory": "2000Mi",
},
"limits": {
"cpu": "3000",
"memory": "4000Mi",
},
}
def set_resources(deployable_details: DeployableDetails):
if deployable_details.name == "synapse":
deployable_details.set_helm_values(values, PropertyType.Resources, resources)
iterate_deployables_parts(set_resources, lambda deployable_details: deployable_details.is_synapse_process)
for pod_template_details in iterate_pod_template(await make_templates(values)):
deployable_details = pod_template_details.deployable_details()
if not deployable_details.is_synapse_process:
continue
for container in pod_template_details.pod_template["spec"]["containers"]:
assert "resources" in container, (
f"{pod_template_details.manifest_id} has container {container['name']} without resources"
)
assert resources == container["resources"], (
f"{pod_template_details.manifest_id} has container {container['name']} "
"which doesn't have the expected resources"
)
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_invalid_yaml_in_synapse_additional_fails(values, make_templates):
values["synapse"]["additional"] = {"invalid.yaml": {"config": "not yaml"}}
with pytest.raises(
pyhelm3.errors.FailedToRenderChartError, match="synapse.additional\\['invalid.yaml'\\] is invalid:"
):
await make_templates(values)
def return_synapse_config(templates, filename):
for template in templates:
if template["kind"] == "ConfigMap" and "synapse" in template["metadata"]["name"]:
synapse_config = template["data"][filename]
return yaml.safe_load(synapse_config)
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_synapse_with_no_workers_doesnt_render_redis_settings(templates):
synapse_config = return_synapse_config(templates, "04-homeserver-overrides.yaml")
assert "redis" not in synapse_config, (
"Redis was unexpectedly present in the Synapse config when there are no workers"
)
@pytest.mark.parametrize("values_file", ["synapse-worker-example-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_synapse_with_workers_renders_redis_settings(release_name, namespace, templates):
synapse_config = return_synapse_config(templates, "04-homeserver-overrides.yaml")
assert "redis" in synapse_config, "No redis settings in the Synapse config when workers are enabled"
redis_config = synapse_config["redis"]
assert redis_config["enabled"], "Redis not enabled in the Synapse config"
assert redis_config["host"] == f"{release_name}-valkey.{namespace}.svc.cluster.local.", (
"The Redis settings aren't pointing at the in-chart Valkey"
)
assert redis_config["port"] == 6379, "The Redis port isn't correct for the in-chart Valkey"
assert redis_config["dbid"] == 0, "The Redis DB ID isn't correct for Synapse"
assert not redis_config["use_tls"], "The in-chart Valkey doesn't run with TLS"
assert "password" not in redis_config, "The in-chart Valkey doesn't run with authentication"
@pytest.mark.parametrize("values_file", ["synapse-minimal-values.yaml", "synapse-worker-example-values.yaml"])
@pytest.mark.asyncio_cooperative
async def test_synapse_always_uses_external_redis_or_valkey_settings(values, namespace, make_templates):
# Minimal settings
random_suffix = "".join(random.choices(string.ascii_lowercase, k=10))
values["synapse"]["redisOrValkey"] = {"host": "pytest-{{ .Release.Namespace }}-" + random_suffix}
templates = await make_templates(values)
synapse_config = return_synapse_config(templates, "04-homeserver-overrides.yaml")
assert "redis" in synapse_config, "No redis settings in the Synapse config when provided by values"
redis_config = synapse_config["redis"]
assert redis_config["enabled"], "Redis not enabled in the Synapse config"
assert redis_config["host"] == f"pytest-{namespace}-{random_suffix}", (
"The Redis settings aren't pointing at the configured host after templating"
)
assert redis_config["port"] == 6379, "The Redis port hasn't defaulted correctly when omitted in the values"
assert redis_config["dbid"] == 0, "The Redis DB ID hasn't defaulted correctly when omitted in the values"
assert not redis_config["use_tls"], (
"The Redis TLS settings hasn't default correctly omitted when omitted in the values"
)
assert "password" not in redis_config, "The Redis password hasn't been omitted when omitted in the values"
# With optional settings added in
values["synapse"]["redisOrValkey"] |= {
"port": random.randint(1000, 2000),
"db": random.randint(1, 15),
"tls": True,
"password": {"value": "".join(random.choices(string.ascii_lowercase, k=10))},
}
templates = await make_templates(values)
synapse_config = return_synapse_config(templates, "04-homeserver-overrides.yaml")
assert "redis" in synapse_config, "No redis settings in the Synapse config when provided by values"
redis_config = synapse_config["redis"]
expected_redis = values["synapse"]["redisOrValkey"]
assert redis_config["enabled"], "Redis not enabled in the Synapse config"
assert redis_config["host"] == f"pytest-{namespace}-{random_suffix}", (
"The Redis settings aren't pointing at the configured host after templating"
)
assert redis_config["port"] == expected_redis["port"], "The Redis port hasn't been configured correctly"
assert redis_config["dbid"] == expected_redis["db"], "The Redis DB ID hasn't been configured correctly"
assert redis_config["use_tls"] == expected_redis["tls"], "The Redis TLS settings haven't been configured correctly"
assert redis_config["password"] == "${SYNAPSE_REDIS_PASSWORD}", (
"The Redis password hasn't been configured to be the environment variable for replacing"
)