Make it possible to fetch Helm values from another locatiion while disallowing setting in the manifest tests

This commit is contained in:
Ben Banfield-Zanin committed 2025-05-23 16:46:21 +01:00
1 parent 4b29ad37d0
commit 5138b0becc
5 files changed
+110 -126

No files matched your search

+1
View File
@@ -0,0 +1 @@
Make it easier to write manifest tests where sub-components and sidecars read values from their parent component.
+91 -86
View File
@@ -26,6 +26,30 @@ class PropertyType(Enum):
TopologySpreadConstraints = "topologySpreadConstraints"
@dataclass
class ValuesFilePath:
write_path: tuple[str, ...] | None
read_path: tuple[str, ...] | None
@classmethod
def not_supported(cls):
return ValuesFilePath(None, None)
@classmethod
def read_write(cls, *path: str):
return ValuesFilePath(tuple(path), tuple(path))
@classmethod
def read_elsewhere(cls, *read_path: str):
return ValuesFilePath(None, tuple(read_path))
def with_property_type(self, propertyType: PropertyType):
return ValuesFilePath(
self.write_path + (propertyType.value,) if self.write_path is not None else None,
self.read_path + (propertyType.value,) if self.read_path is not None else None,
)
# We introduce 4 DataClasses to store details of the deployables this chart manages
# * ComponentDetails - details of a top-level deployable. This includes both the headline
# components like Synapse, Element Web, etc and components that have their own independent
@@ -61,12 +85,10 @@ class DeployableDetails(abc.ABC):
value_file_prefix: str | None = field(default=None, hash=False)
# The "path" through the values file that properties for this deployable will be rooted at
# by default. The PropertyType value will then finish off the "path".
helm_keys: tuple[str, ...] = field(default=None, hash=False) # type: ignore[arg-type]
values_file_path: ValuesFilePath = field(default=None, hash=False) # type: ignore[assignment]
# Per-PropertyType (ingress, env, etc) overrides for the "path" through the values file
# that should be used for that specific PropertyType. A path of None for a given PropertyType
# means this deployable can't set values of that property type. That doesn't mean that the
# deployable won't have e.g. env vars, it means they will be sourced from their parent.
helm_keys_overrides: dict[PropertyType, tuple[str, ...] | None] | None = field(default=None, hash=False)
# that should be used for that specific PropertyType.
values_file_path_overrides: dict[PropertyType, ValuesFilePath] | None = field(default=None, hash=False)
has_db: bool = field(default=False, hash=False)
has_image: bool = field(default=None, hash=False) # type: ignore[assignment]
@@ -81,8 +103,8 @@ class DeployableDetails(abc.ABC):
skip_path_consistency_for_files: tuple[str, ...] = field(default=(), hash=False)
def __post_init__(self):
if self.helm_keys is None or len(self.helm_keys) == 0:
self.helm_keys = (self.name,)
if self.values_file_path is None:
self.values_file_path = ValuesFilePath.read_write(self.name)
if self.has_image is None:
self.has_image = self.has_workloads
if self.has_service_monitor is None:
@@ -90,21 +112,17 @@ class DeployableDetails(abc.ABC):
if self.has_topology_spread_constraints is None:
self.has_topology_spread_constraints = self.has_workloads
def _get_helm_keys(self, propertyType: PropertyType) -> tuple[str, ...] | None:
def _get_values_file_path(self, propertyType: PropertyType) -> ValuesFilePath:
"""
Returns the "path" (tuple of values keys) to a given PropertyType.
Returns the "path" through the values file to a given PropertyType.
Returns None if this deployable has an override explicitly set to None to indicated
that this deployable doesn't have its own values for that PropertyType.
The path may exist for both reading and writing, writing only or not at all, but that's
all encapsulated in ValuesFilePath
"""
if (
propertyType is not None
and self.helm_keys_overrides is not None
and propertyType in self.helm_keys_overrides
):
return self.helm_keys_overrides[propertyType]
if self.values_file_path_overrides is not None and propertyType in self.values_file_path_overrides:
return self.values_file_path_overrides[propertyType]
else:
return self.helm_keys + (propertyType.value,)
return self.values_file_path.with_property_type(propertyType)
def get_helm_values(
self, values: dict[str, Any], propertyType: PropertyType, default_value: Any = None
@@ -118,16 +136,16 @@ class DeployableDetails(abc.ABC):
* None if this deployable explicitly can't configure this PropertyType.
* The value or empty dict if this PropertyType can be configured.
"""
helm_keys = self._get_helm_keys(propertyType)
if helm_keys is None:
values_file_path = self._get_values_file_path(propertyType)
if values_file_path.read_path is None:
return None
values_fragment = values
for index, helm_key in enumerate(helm_keys):
for index, helm_key in enumerate(values_file_path.read_path):
# The last iteration through is the specific property we want to get. We know everything
# higher this will be a dict, but at the end, for a specific property, we could be
# trying to fetch an object, an array or a scalar and the default value should reflect that
if (index + 1) == len(helm_keys):
if (index + 1) == len(values_file_path.read_path):
if default_value is None:
default_value = {}
values_fragment = values_fragment.setdefault(helm_key, default_value)
@@ -148,16 +166,16 @@ class DeployableDetails(abc.ABC):
is to support the case where sub-components/sidecars obtain values from their parent and so
can't set those PropertyTypes themselves.
"""
helm_keys = self._get_helm_keys(propertyType)
if helm_keys is None:
values_file_path = self._get_values_file_path(propertyType)
if values_file_path.write_path is None:
return
values_fragment = values
for index, helm_key in enumerate(helm_keys):
for index, helm_key in enumerate(values_file_path.write_path):
# The last iteration through is the specific property we want to set. We know everything
# higher this will be a dict, but at the end, for a specific property, we could be
# trying to set an object, an array or even a scalar
if (index + 1) == len(helm_keys):
if (index + 1) == len(values_file_path.write_path):
if isinstance(values_to_set, dict):
values_fragment.setdefault(propertyType.value, {}).update(values_to_set)
elif isinstance(values_to_set, list):
@@ -183,16 +201,16 @@ class SidecarDetails(DeployableDetails):
def __post_init__(self):
super().__post_init__()
sidecar_helm_keys_overrides = {
sidecar_values_file_path_overrides = {
# Not possible, will come from the parent component
PropertyType.PodSecurityContext: None,
PropertyType.ServiceAccount: None,
PropertyType.Tolerations: None,
PropertyType.TopologySpreadConstraints: None,
PropertyType.PodSecurityContext: ValuesFilePath.not_supported(),
PropertyType.ServiceAccount: ValuesFilePath.not_supported(),
PropertyType.Tolerations: ValuesFilePath.not_supported(),
PropertyType.TopologySpreadConstraints: ValuesFilePath.not_supported(),
}
if self.helm_keys_overrides is None:
self.helm_keys_overrides = {}
self.helm_keys_overrides |= sidecar_helm_keys_overrides
if self.values_file_path_overrides is None:
self.values_file_path_overrides = {}
self.values_file_path_overrides |= sidecar_values_file_path_overrides
# Not possible, will come from the parent components
self.has_topology_spread_constraints = False
@@ -304,30 +322,21 @@ class ComponentDetails(DeployableDetails):
def make_synapse_worker_sub_component(worker_name: str) -> SubComponentDetails:
helm_keys_overrides: dict[PropertyType, tuple[str, ...] | None] = {
# Doesn't have its own env, comes from synapse.extraEnv
PropertyType.Env: None,
# Doesn't have its own image, comes from synapse.image
PropertyType.Image: None,
# Doesn't have its own labels, comes from synapse.labels
PropertyType.Labels: None,
# Doesn't have its own podSecurityContext, comes from synapse.podSecurityContext
PropertyType.PodSecurityContext: None,
# Doesn't have its own serviceAccount, comes from synapse.serviceAccount
PropertyType.ServiceAccount: None,
# Doesn't have its own serviceMonitor, comes from synapse.serviceMonitor
PropertyType.ServiceMonitor: None,
# has_workloads and so tolerations but comes from synapse.tolerations
PropertyType.Tolerations: None,
# has_topology_spread_constraints and so topologySpreadConstraints
# but comes from synapse.topologySpreadConstraints
PropertyType.TopologySpreadConstraints: None,
values_file_path_overrides: dict[PropertyType, ValuesFilePath] = {
PropertyType.Env: ValuesFilePath.read_elsewhere("synapse", "extraEnv"),
PropertyType.Image: ValuesFilePath.read_elsewhere("synapse", "image"),
PropertyType.Labels: ValuesFilePath.read_elsewhere("synapse", "labels"),
PropertyType.PodSecurityContext: ValuesFilePath.read_elsewhere("synapse", "podSecurityContext"),
PropertyType.ServiceAccount: ValuesFilePath.read_elsewhere("synapse", "serviceAccount"),
PropertyType.ServiceMonitor: ValuesFilePath.read_elsewhere("synapse", "serviceMonitor"),
PropertyType.Tolerations: ValuesFilePath.read_elsewhere("synapse", "tolerations"),
PropertyType.TopologySpreadConstraints: ValuesFilePath.read_elsewhere("synapse", "topologySpreadConstraints"),
}
return SubComponentDetails(
f"synapse-{worker_name}",
helm_keys=("synapse", "workers", worker_name),
helm_keys_overrides=helm_keys_overrides,
values_file_path=ValuesFilePath.read_write("synapse", "workers", worker_name),
values_file_path_overrides=values_file_path_overrides,
has_ingress=False,
is_synapse_process=True,
)
@@ -363,14 +372,14 @@ synapse_workers_details = tuple(
all_components_details = [
ComponentDetails(
name="init-secrets",
helm_keys=("initSecrets",),
helm_keys_overrides={
values_file_path=ValuesFilePath.read_write("initSecrets"),
values_file_path_overrides={
# Job so no livenessProbe
PropertyType.LivenessProbe: None,
PropertyType.LivenessProbe: ValuesFilePath.not_supported(),
# Job so no readinessProbe
PropertyType.ReadinessProbe: None,
PropertyType.ReadinessProbe: ValuesFilePath.not_supported(),
# Job so no startupProbe
PropertyType.StartupProbe: None,
PropertyType.StartupProbe: ValuesFilePath.not_supported(),
},
has_image=False,
has_ingress=False,
@@ -391,10 +400,10 @@ all_components_details = [
sidecars=(
SidecarDetails(
name="postgres-exporter",
helm_keys=("postgres", "postgresExporter"),
helm_keys_overrides={
values_file_path=ValuesFilePath.read_write("postgres", "postgresExporter"),
values_file_path_overrides={
# No manifests of its own, so no labels to set
PropertyType.Labels: None,
PropertyType.Labels: ValuesFilePath.not_supported(),
},
has_ingress=False,
has_service_monitor=False,
@@ -405,12 +414,12 @@ all_components_details = [
),
ComponentDetails(
name="matrix-rtc",
helm_keys=("matrixRTC",),
values_file_path=ValuesFilePath.read_write("matrixRTC"),
has_topology_spread_constraints=False,
sub_components=(
SubComponentDetails(
name="matrix-rtc-sfu",
helm_keys=("matrixRTC", "sfu"),
values_file_path=ValuesFilePath.read_write("matrixRTC", "sfu"),
has_topology_spread_constraints=False,
has_ingress=False,
),
@@ -423,7 +432,7 @@ all_components_details = [
),
ComponentDetails(
name="element-web",
helm_keys=("elementWeb",),
values_file_path=ValuesFilePath.read_write("elementWeb"),
has_service_monitor=False,
paths_consistency_noqa=(
# Explicitly mounted but wildcard included by the base-image
@@ -443,7 +452,7 @@ all_components_details = [
),
ComponentDetails(
name="matrix-authentication-service",
helm_keys=("matrixAuthenticationService",),
values_file_path=ValuesFilePath.read_write("matrixAuthenticationService"),
has_db=True,
shared_component_names=("init-secrets", "postgres"),
),
@@ -458,34 +467,30 @@ all_components_details = [
+ (
SubComponentDetails(
name="synapse-redis",
helm_keys=("synapse", "redis"),
values_file_path=ValuesFilePath.read_write("synapse", "redis"),
has_ingress=False,
has_service_monitor=False,
has_topology_spread_constraints=False,
),
SubComponentDetails(
name="synapse-check-config-hook",
helm_keys=("synapse", "checkConfigHook"),
helm_keys_overrides={
# has_workloads but comes from synapse.extraEnv
PropertyType.Env: None,
# has_workloads but comes from synapse.image
PropertyType.Image: None,
values_file_path=ValuesFilePath.read_write("synapse", "checkConfigHook"),
values_file_path_overrides={
PropertyType.Env: ValuesFilePath.read_elsewhere("synapse", "extraEnv"),
PropertyType.Image: ValuesFilePath.read_elsewhere("synapse", "image"),
# Job so no livenessProbe
PropertyType.LivenessProbe: None,
# has_workloads and so podSecurityContext but comes from synapse.podSecurityContext
PropertyType.PodSecurityContext: None,
# has_workloads but comes from synapse.resources
PropertyType.Resources: None,
PropertyType.LivenessProbe: ValuesFilePath.not_supported(),
PropertyType.PodSecurityContext: ValuesFilePath.read_elsewhere("synapse", "podSecurityContext"),
PropertyType.Resources: ValuesFilePath.read_elsewhere("synapse", "resources"),
# Job so no readinessProbe
PropertyType.ReadinessProbe: None,
PropertyType.ReadinessProbe: ValuesFilePath.not_supported(),
PropertyType.ServiceMonitor: ValuesFilePath.read_elsewhere("synapse", "serviceMonitor"),
# Job so no startupProbe
PropertyType.StartupProbe: None,
# has_workloads and so tolerations but comes from synapse.tolerations
PropertyType.Tolerations: None,
# has_topology_spread_constraints and so topologySpreadConstraints
# but comes from synapse.topologySpreadConstraints
PropertyType.TopologySpreadConstraints: None,
PropertyType.StartupProbe: ValuesFilePath.not_supported(),
PropertyType.Tolerations: ValuesFilePath.read_elsewhere("synapse", "tolerations"),
PropertyType.TopologySpreadConstraints: ValuesFilePath.read_elsewhere(
"synapse", "topologySpreadConstraints"
),
},
has_ingress=False,
has_service_monitor=False,
@@ -495,7 +500,7 @@ all_components_details = [
),
ComponentDetails(
name="well-known",
helm_keys=("wellKnownDelegation",),
values_file_path=ValuesFilePath.read_write("wellKnownDelegation"),
has_workloads=False,
shared_component_names=("haproxy",),
),
+4 -4
View File
@@ -66,10 +66,10 @@ async def test_templates_have_postgres_hash_label(release_name, templates, value
continue
assert "k8s.element.io/postgres-password-hash" in labels, f"{id} does not have postgres password hash label"
assert (
len(deployable_details.helm_keys) == 1
) # We currently assume that Postgres is for top-level components only
helm_key = deployable_details.helm_keys[0]
# We currently assume that Postgres is for top-level components only and so there is a single segment
# write (or read) path
assert len(deployable_details.values_file_path.write_path) == 1
helm_key = deployable_details.values_file_path.read_path[0]
values_fragment = deployable_details.get_helm_values(values, PropertyType.Postgres)
if values_fragment.get("password", {}).get("value", None):
expected = values_fragment["password"]["value"]
+13 -27
View File
@@ -86,8 +86,6 @@ def assert_sensible_default_probe(template, probe_type):
def set_probe_details(values, probe_type):
deployable_details_to_probe_details = {}
# We have a counter that increments for each probe field for each deployable details
# That way we can assert a) the correct value is going into the correct field and
# b) that the correct part of the values file is being used
@@ -106,21 +104,24 @@ def set_probe_details(values, probe_type):
"timeoutSeconds": counter + 4,
}
counter += 5
deployable_details_to_probe_details[deployable_details] = probe_details
deployable_details.set_helm_values(values, probe_type, probe_details)
iterate_deployables_workload_parts(set_probe_details)
return deployable_details_to_probe_details
def assert_matching_probe(template, probe_type, deployable_details_to_probe_details, template_to_deployable_details):
def assert_matching_probe(template, probe_type, values, template_to_deployable_details):
for container in template["spec"]["template"]["spec"]["containers"]:
assert probe_type in container, (
f"{template_id(template)} has container {container['name']} without a {probe_type}"
)
deployable_details = template_to_deployable_details(template, container["name"])
probe_details = deployable_details_to_probe_details[deployable_details]
probe_types_to_property_types = {
"livenessProbe": PropertyType.LivenessProbe,
"readinessProbe": PropertyType.ReadinessProbe,
"startupProbe": PropertyType.StartupProbe,
}
probe_details = deployable_details.get_helm_values(values, probe_types_to_property_types[probe_type])
probe = container[probe_type]
for key, value in probe_details.items():
@@ -150,15 +151,10 @@ async def test_sensible_livenessProbes_by_default(templates):
@pytest.mark.parametrize("values_file", values_files_to_test)
@pytest.mark.asyncio_cooperative
async def test_livenessProbes_are_configurable(values, make_templates, template_to_deployable_details):
deployable_details_to_probe_details = set_probe_details(values, PropertyType.LivenessProbe)
set_probe_details(values, PropertyType.LivenessProbe)
for template in await make_templates(values):
if template["kind"] in ["Deployment", "StatefulSet"]:
assert_matching_probe(
template,
"livenessProbe",
deployable_details_to_probe_details,
template_to_deployable_details,
)
assert_matching_probe(template, "livenessProbe", values, template_to_deployable_details)
@pytest.mark.parametrize("values_file", values_files_to_test)
@@ -172,15 +168,10 @@ async def test_sensible_readinessProbes_by_default(templates):
@pytest.mark.parametrize("values_file", values_files_to_test)
@pytest.mark.asyncio_cooperative
async def test_readinessProbes_are_configurable(values, make_templates, template_to_deployable_details):
deployable_details_to_probe_details = set_probe_details(values, PropertyType.ReadinessProbe)
set_probe_details(values, PropertyType.ReadinessProbe)
for template in await make_templates(values):
if template["kind"] in ["Deployment", "StatefulSet"]:
assert_matching_probe(
template,
"readinessProbe",
deployable_details_to_probe_details,
template_to_deployable_details,
)
assert_matching_probe(template, "readinessProbe", values, template_to_deployable_details)
@pytest.mark.parametrize("values_file", values_files_to_test)
@@ -194,12 +185,7 @@ async def test_sensible_startupProbes_by_default(templates):
@pytest.mark.parametrize("values_file", values_files_to_test)
@pytest.mark.asyncio_cooperative
async def test_startupProbes_are_configurable(values, make_templates, template_to_deployable_details):
deployable_details_to_probe_details = set_probe_details(values, PropertyType.StartupProbe)
set_probe_details(values, PropertyType.StartupProbe)
for template in await make_templates(values):
if template["kind"] in ["Deployment", "StatefulSet"]:
assert_matching_probe(
template,
"startupProbe",
deployable_details_to_probe_details,
template_to_deployable_details,
)
assert_matching_probe(template, "startupProbe", values, template_to_deployable_details)
+1 -9
View File
@@ -11,7 +11,6 @@ from .utils import iterate_deployables_workload_parts, template_id
@pytest.mark.parametrize("values_file", values_files_to_test)
@pytest.mark.asyncio_cooperative
async def test_pod_resources_are_configurable(values, make_templates, template_to_deployable_details):
deployable_details_to_resources = {}
counter = 1
def set_resources(deployable_details: DeployableDetails):
@@ -27,7 +26,6 @@ async def test_pod_resources_are_configurable(values, make_templates, template_t
},
}
counter += 1
deployable_details_to_resources[deployable_details] = resources
deployable_details.set_helm_values(values, PropertyType.Resources, resources)
iterate_deployables_workload_parts(set_resources)
@@ -39,14 +37,8 @@ async def test_pod_resources_are_configurable(values, make_templates, template_t
)
deployable_details = template_to_deployable_details(template, container["name"])
expected_resources = deployable_details.get_helm_values(values, PropertyType.Resources)
# The check config job gets its resources from Synapse and doesn't have its own values
# We don't have a good way of "redirecting" to Synapse's expected resources so just skip
# test_synapse_resources_shared_by_default tests that the check config job uses synapse.resources
if deployable_details.name == "synapse-check-config-hook":
continue
expected_resources = deployable_details_to_resources[deployable_details]
assert expected_resources == container["resources"], (
f"{template_id(template)} has container {container['name']} "
"which doesn't have the expected resources"