Add a name to Strategies

- Strategies name are used to identifiy them
- We do not need component_root_key anymore excepted for the
ExtraFileDiscoveryStrategy
- The additional is not done using a closure which passes the
appropriate properties to the transformer
This commit is contained in:
Gaël Goinvic committed 2026-04-22 11:31:33 +02:00
1 parent 0bbfdaf6c2
commit 55f331af62
10 files changed
+141 -118

No files matched your search

@@ -14,9 +14,10 @@ from dataclasses import dataclass, field
from .engine import MigrationEngine
from .inputs import InputProcessor, ValidationError
from .mas import parse_postgres_uri
from .mas import MAS_STRATEGY_NAME, parse_postgres_uri
from .models import MigrationError
from .outputs import generate_helm_values, write_outputs
from .synapse import SYNAPSE_STRATEGY_NAME
from .utils import delay_next_steps, prompt_for_database_choice
LOADING_STEP = "Loading and validating input files"
@@ -179,13 +180,13 @@ Examples:
reporter.report_step(LOADING_STEP)
input_processor = InputProcessor()
input_processor.load_migration_input(
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
config_path=args.synapse_config,
)
if args.mas_config:
input_processor.load_migration_input(
name="matrixAuthenticationService",
name=MAS_STRATEGY_NAME,
config_path=args.mas_config,
)
@@ -228,10 +229,10 @@ Examples:
# Process migrations
for migrator in engine.migrators:
# Get the input for this migrator's component
# The input name is the same as the component_root_key stored in the migrator
migration_input = engine.input_processor.input_for_component(migrator.component_root_key)
# Migrators are created according to discovered input for components, we do not expect NoneTypes here
# Get the input for this migrator's strategy
# The input name is the same as the strategy name
migration_input = engine.input_processor.input_for_strategy(migrator.migration.name)
# Migrators are created according to discovered input for strategies, we do not expect NoneTypes here
assert migration_input
source_file = migration_input.config_path
for transformation_result in migrator.results:
@@ -335,7 +336,7 @@ Examples:
delay_next_steps(pretty_logger)
# Get the original media path from Synapse configuration
synapse_input = engine.input_processor.input_for_component("synapse")
synapse_input = engine.input_processor.input_for_strategy(SYNAPSE_STRATEGY_NAME)
original_media_path = None
if synapse_input and synapse_input.config.get("media_store_path"):
original_media_path = synapse_input.config["media_store_path"]
@@ -357,8 +358,8 @@ Examples:
delay_next_steps(pretty_logger)
# Get source database configuration from input files
synapse_input = engine.input_processor.input_for_component("synapse")
mas_input = engine.input_processor.input_for_component("matrixAuthenticationService")
synapse_input = engine.input_processor.input_for_strategy(SYNAPSE_STRATEGY_NAME)
mas_input = engine.input_processor.input_for_strategy(MAS_STRATEGY_NAME)
# Extract source database info from Synapse configuration
assert synapse_input
@@ -39,20 +39,19 @@ class MigrationEngine:
"""Initialize the migration engine."""
components = [
(
"synapse",
SynapseMigration(self.global_options),
SynapseSecretDiscovery(self.global_options),
SynapseExtraFileDiscovery(),
),
(
"matrixAuthenticationService",
MASMigration(self.global_options),
MASSecretDiscovery(self.global_options),
MASExtraFileDiscovery(),
),
]
for component_key, migration, secret_discovery_strategy, extra_file_strategy in components:
migration_input = self.input_processor.input_for_component(component_key)
for migration, secret_discovery_strategy, extra_file_strategy in components:
strategy_name = migration.name
migration_input = self.input_processor.input_for_strategy(strategy_name)
if migration_input:
self.migrators.append(
MigrationService(
@@ -62,7 +61,6 @@ class MigrationEngine:
migration=migration,
extra_files_strategy=extra_file_strategy,
secret_discovery_strategy=secret_discovery_strategy,
component_root_key=component_key,
secrets=self.secrets,
configmaps=self.configmaps,
global_options=self.global_options,
@@ -32,12 +32,18 @@ class InputProcessor:
inputs: list[MigrationInput] = field(default_factory=list)
def input_for_component(self, component_root_key: str) -> MigrationInput | None:
def input_for_strategy(self, strategy_name: str) -> MigrationInput | None:
"""
Return the migration input for a component.
Return the migration input for a strategy.
Args:
strategy_name: The user-facing strategy name (e.g., "Synapse", "Matrix Authentication Service")
Returns:
MigrationInput for the strategy, or None if not found
"""
for _input in self.inputs:
if _input.name == component_root_key:
if _input.name == strategy_name:
return _input
return None
@@ -13,13 +13,14 @@ import urllib
from typing import Any
from .interfaces import ExtraFilesDiscoveryStrategy, SecretDiscoveryStrategy
from .migration import MigrationStrategy, TransformationSpec, additional_config_transformer
from .migration import ConfigValueTransformer, MigrationStrategy, TransformationSpec, additional_config_transformer
from .models import DiscoveredSecret, GlobalOptions, SecretConfig
from .utils import detect_key_type, extract_hostname_from_url, yaml_dump_with_pipe_for_multiline
logger = logging.getLogger("migration")
MAS_STRATEGY_NAME = "Matrix Authentication Service"
MAS_COMPONENT_ROOT_KEY = "matrixAuthenticationService"
def parse_postgres_uri(uri: str) -> dict[str, Any]:
@@ -224,7 +225,29 @@ class MASMigration(MigrationStrategy):
@property
def transformations(self) -> list[TransformationSpec]:
"""Get transformations based on database choice."""
# Lambda to wrap additional_config_transformer with MAS-specific context
def mas_additional_transformer(
config_value_transformer: "ConfigValueTransformer",
value: Any,
**kwargs: Any,
) -> dict[str, Any]:
return additional_config_transformer(
config_value_transformer,
value,
component_root_key=MAS_COMPONENT_ROOT_KEY,
override_configs=self.override_configs,
component_name=MAS_STRATEGY_NAME,
**kwargs,
)
base_transformations = [
# Enable MAS component
TransformationSpec(
src_key=None,
target_key="matrixAuthenticationService.enabled",
transformer=lambda *_, **__: True,
),
TransformationSpec(
src_key="http.public_base",
target_key="matrixAuthenticationService.ingress.host",
@@ -239,7 +262,7 @@ class MASMigration(MigrationStrategy):
TransformationSpec(
src_key=None,
target_key="matrixAuthenticationService.additional",
transformer=additional_config_transformer,
transformer=mas_additional_transformer,
required=False,
), # Generic additional config generation (src_key=None passes full config)
# ... other non-database transformations ...
@@ -51,13 +51,16 @@ def additional_config_transformer(
kwargs uses:
- extra_files_discovery: ExtraFilesDiscovery | None containing the extra files discovery service
- component_root_key: str - Internal ESS config key (e.g., "synapse")
- override_configs: set[str] - Set of configuration paths managed by ESS
- component_name: str - User-facing strategy name (e.g., "Synapse")
"""
source_config = value # value is the source config (when src_key is None)
# Get context from kwargs
component_root_key = kwargs.get("component_root_key", "")
override_configs = kwargs.get("override_configs", set())
extra_files_discovery = kwargs.get("extra_files_discovery")
if extra_files_discovery:
component_root_key = extra_files_discovery.strategy.component_root_key
else:
component_root_key = kwargs.get("component_root_key", "")
filtered_config = copy.deepcopy(source_config)
@@ -65,11 +68,20 @@ def additional_config_transformer(
for source_path in config_value_transformer.tracked_values:
remove_nested_value(filtered_config, source_path)
# Note: This runs after filtering so we check the remaining config
# Get all src_keys from transformations that have been processed
# Store warnings for future engine logging
if override_configs and component_root_key:
for override_config in override_configs:
if get_nested_value(filtered_config, override_config) is not None:
warning = (
f"⚠️ '{override_config}' found in {component_root_key}.additional[\"00-imported.yaml\"].config"
)
config_value_transformer.override_warnings.append(warning)
# Update file paths if extra files were discovered
if extra_files_discovery:
filtered_config = config_value_transformer.update_paths_in_config(
filtered_config, extra_files_discovery, component_root_key
)
filtered_config = config_value_transformer.update_paths_in_config(filtered_config, extra_files_discovery)
# Return in the expected additional config format
# Also preserve any existing entries in additional (like listeners.yml from other transformers)
@@ -111,13 +123,14 @@ class ConfigValueTransformer:
ess_config: dict[str, Any] = field(init=True) # Target ESS configuration dictionary
results: list[TransformationResult] = field(default_factory=list) # List of transformation results
tracked_values: list[str] = field(default_factory=list) # Source paths that have been processed
override_warnings: list[str] = field(default_factory=list) # Warnings about ESS-managed overrides
def transform_from_config(
self,
source_config: dict[str, Any],
transformations: list[TransformationSpec],
component_root_key: str = "",
extra_files_discovery: ExtraFilesDiscovery | None = None,
**kwargs: Any,
) -> None:
"""
Transform values from a source configuration using explicit source and target path mappings.
@@ -125,8 +138,8 @@ class ConfigValueTransformer:
Args:
source_config: Source configuration dictionary
transformations: List of TransformationSpec objects
component_root_key: Component root key for context (e.g., "synapse")
extra_files_discovery: ExtraFilesDiscovery instance for context
**kwargs: Additional context to pass to transformer functions
"""
for transformation in transformations:
# Get the value from the source configuration
@@ -143,8 +156,8 @@ class ConfigValueTransformer:
transformed_value = transformation.transformer(
self,
value,
component_root_key=component_root_key,
extra_files_discovery=extra_files_discovery,
**kwargs,
)
else:
# No transformer provided, use the raw value
@@ -207,10 +220,9 @@ class ConfigValueTransformer:
self,
source_config: dict[str, Any],
extra_files_discovery: ExtraFilesDiscovery,
component_root_key: str,
):
# Get the base mount path for the component
base_mount_path = f"/etc/{component_root_key}/extra"
base_mount_path = f"/etc/{extra_files_discovery.strategy.component_root_key}/extra"
updated_config = copy.deepcopy(source_config)
for discovered_path in extra_files_discovery.discovered_file_paths:
if discovered_path.skipped_reason:
@@ -360,7 +372,6 @@ class MigrationService:
migration: MigrationStrategy = field(init=True) # Migration strategy
extra_files_strategy: ExtraFilesDiscoveryStrategy = field(init=True) # Extra files discovery service
secret_discovery_strategy: SecretDiscoveryStrategy = field(init=True) # Secret discovery service
component_root_key: str = field(init=True) # Root key for the component (e.g., 'synapse')
override_warnings: list[str] = field(default_factory=list) # Warnings about overridden configurations
init_by_ess_secrets: list[str] = field(default_factory=list) # List of secrets that will be initialized by ESS
discovered_secrets: list[DiscoveredSecret] = field(default_factory=list) # List of discovered secrets
@@ -374,56 +385,13 @@ class MigrationService:
def __post_init__(self):
self.override_configs = self.migration.override_configs
def _check_overrides(self, config: dict[str, Any], config_to_ess_transformer: ConfigValueTransformer) -> None:
"""
Check if the configuration contains any override configurations
that are managed by ESS and cannot be overridden.
Only shows overrides that are managed by ESS chart (no direct transformation).
Settings with transformations are already shown in "Successfully migrated" section.
Args:
config: Configuration to check
config_to_ess_transformer: Transformer containing tracked values for filtering
"""
override_warnings = []
# Build set of transformed config paths for filtering
transformed_configs = set()
for transformation in self.migration.transformations:
transformed_configs.add(transformation.src_key)
# Use the filtered configuration (with migrated values removed) for override detection
# This automatically excludes values that are tracked by the transformer,
# including both regular transformations and secrets (which are added to tracked_values during handle_secrets)
filtered_config = config_to_ess_transformer.filter_config(config)
for override_config in self.override_configs:
# Check if the override config path exists in the filtered configuration
# and is managed by ESS chart (no direct transformation)
if (
get_nested_value(filtered_config, override_config) is not None
and override_config not in transformed_configs
):
override_warnings.append(
f"⚠️ '{override_config}' found in {self.component_root_key}.additional[\"00-imported.yaml\"].config"
)
if override_warnings:
self.override_warnings.extend(override_warnings)
logger.warning(f"{self.component_root_key} configuration contains ESS-managed overrides:")
for warning in override_warnings:
logger.warning(warning)
def migrate(self) -> None:
"""
Perform migration using the injected strategy.
Migration steps:
1. Enable component
1. Apply component transformations
2. Check for override configurations
3. Add filtered additional configurations
2. Add filtered additional configurations
"""
# Step 1: Discover secrets
secret_discovery = SecretDiscovery(
@@ -454,37 +422,32 @@ class MigrationService:
self.discovered_file_paths = extra_files_discovery.discovered_file_paths
self.missing_file_paths = extra_files_discovery.missing_file_paths
# Step 3: Enable component
self.ess_config.setdefault(self.component_root_key, {})["enabled"] = True
config_to_ess_transformer = ConfigValueTransformer(self.pretty_logger, self.ess_config)
# Step 4: Handle secrets for the component using the transformer's method
# Step 3: Handle secrets for the component using the transformer's method
# This will update the root ESS config directly and create Kubernetes Secrets
config_to_ess_transformer.handle_secrets(
secret_discovery,
self.component_root_key,
self.extra_files_strategy.component_root_key,
self.secrets,
)
# Step 5: Handle extra files mounts for the component using the transformer's method
# Step 4: Handle extra files mounts for the component using the transformer's method
# This will update the root ESS config directly and create Kubernetes ConfigMaps
config_to_ess_transformer.handle_extra_files_mounts(
extra_files_discovery,
self.component_root_key,
self.extra_files_strategy.component_root_key,
self.configmaps,
)
# Step 6: Apply component transformations
# Step 5: Apply component transformations
# Note: component_root_key and other context are passed through TransformationSpec lambdas
config_to_ess_transformer.transform_from_config(
self.input.config,
self.migration.transformations,
component_root_key=self.component_root_key,
extra_files_discovery=extra_files_discovery,
)
# Step 7: Check for override configurations and warn user
self._check_overrides(self.input.config, config_to_ess_transformer)
# Step 8: Store results
# Step 6: Store results and override warnings
self.results.extend(config_to_ess_transformer.results)
self.override_warnings.extend(config_to_ess_transformer.override_warnings)
@@ -21,6 +21,7 @@ from .utils import extract_hostname_from_url, yaml_dump_with_pipe_for_multiline
logger = logging.getLogger("migration")
SYNAPSE_STRATEGY_NAME = "Synapse"
SYNAPSE_COMPONENT_ROOT_KEY = "synapse"
worker_types = [
"main",
@@ -301,7 +302,29 @@ class SynapseMigration(MigrationStrategy):
@property
def transformations(self) -> list[TransformationSpec]:
"""Get transformations based on database choice."""
# Lambda to wrap additional_config_transformer with Synapse-specific context
def synapse_additional_transformer(
config_value_transformer: "ConfigValueTransformer",
value: Any,
**kwargs: Any,
) -> dict[str, Any]:
return additional_config_transformer(
config_value_transformer,
value,
component_root_key=SYNAPSE_COMPONENT_ROOT_KEY,
override_configs=self.override_configs,
component_name=SYNAPSE_STRATEGY_NAME,
**kwargs,
)
base_transformations = [
# Enable Synapse component
TransformationSpec(
src_key=None,
target_key="synapse.enabled",
transformer=lambda *_, **__: True,
),
TransformationSpec(src_key="server_name", target_key="serverName"),
TransformationSpec(
src_key="public_baseurl",
@@ -323,7 +346,7 @@ class SynapseMigration(MigrationStrategy):
TransformationSpec(
src_key=None,
target_key="synapse.additional",
transformer=additional_config_transformer,
transformer=synapse_additional_transformer,
required=False,
), # Generic additional config generation (src_key=None passes full config)
# ... other non-database transformations ...
@@ -38,7 +38,6 @@ line3""",
transformer.transform_from_config(
source_config,
[spec],
component_root_key="synapse",
extra_files_discovery=None,
)
@@ -70,7 +69,6 @@ def test_additional_config_transformer_single_line_no_unnecessary_pipe():
transformer.transform_from_config(
source_config,
[spec],
component_root_key="synapse",
extra_files_discovery=None,
)
@@ -107,7 +105,6 @@ formatters:
transformer.transform_from_config(
source_config,
[spec],
component_root_key="synapse",
extra_files_discovery=None,
)
@@ -163,7 +160,6 @@ def test_additional_config_transformer_filters_tracked_values():
transformer.transform_from_config(
source_config,
[spec1, spec2, spec3],
component_root_key="synapse",
extra_files_discovery=None,
)
@@ -215,7 +211,6 @@ def test_additional_config_transformer_empty_when_all_tracked():
transformer.transform_from_config(
source_config,
[spec1, spec2, spec3],
component_root_key="synapse",
extra_files_discovery=None,
)
@@ -246,8 +241,8 @@ def test_additional_config_transformer_preserves_existing_additional():
transformer.transform_from_config(
source_config,
[spec],
component_root_key="synapse",
extra_files_discovery=None,
component_root_key="synapse",
)
result = transformer.ess_config
@@ -183,6 +183,10 @@ def test_update_paths_in_config_basic():
def ignored_config_keys(self):
return []
@property
def component_root_key(self):
return "some-component"
class MockSecretStrategy(SecretDiscoveryStrategy):
def __init__(self, global_options):
self.global_options = global_options
@@ -228,11 +232,11 @@ def test_update_paths_in_config_basic():
)
# Test the update_paths_in_config method
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery, "synapse")
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery)
# Verify paths are updated correctly
assert updated_config["templates"]["password_reset"] == "/etc/synapse/extra/password_reset.html"
assert updated_config["templates"]["registration"] == "/etc/synapse/extra/registration.html"
assert updated_config["templates"]["password_reset"] == "/etc/some-component/extra/password_reset.html"
assert updated_config["templates"]["registration"] == "/etc/some-component/extra/registration.html"
assert updated_config["other_setting"] == "preserved" # Non-file setting should be unchanged
# Verify tracked values (only skipped paths are tracked)
@@ -248,6 +252,10 @@ def test_update_paths_in_config_with_skipped_paths():
def ignored_config_keys(self):
return []
@property
def component_root_key(self):
return "some-component"
class MockSecretStrategy(SecretDiscoveryStrategy):
def __init__(self, global_options):
self.global_options = global_options
@@ -291,11 +299,11 @@ def test_update_paths_in_config_with_skipped_paths():
)
# Test the update_paths_in_config method
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery, "synapse")
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery)
# Verify skipped path is not updated but is tracked
assert updated_config["templates"]["password_reset"] == "/path/to/password_reset.html" # Unchanged
assert updated_config["templates"]["registration"] == "/etc/synapse/extra/registration.html" # Updated
assert updated_config["templates"]["registration"] == "/etc/some-component/extra/registration.html" # Updated
assert "templates.password_reset" not in transformer.tracked_values
assert "templates.registration" not in transformer.tracked_values
@@ -311,6 +319,10 @@ def test_update_paths_in_config_empty_discovery():
def ignored_config_keys(self):
return []
@property
def component_root_key(self):
return "some-component"
class MockSecretStrategy(SecretDiscoveryStrategy):
def __init__(self, global_options):
self.global_options = global_options
@@ -337,7 +349,7 @@ def test_update_paths_in_config_empty_discovery():
)
# Test the update_paths_in_config method
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery, "synapse")
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery)
# Verify config is unchanged
assert updated_config == source_config
@@ -353,6 +365,10 @@ def test_update_paths_in_config_nested_config():
def ignored_config_keys(self):
return []
@property
def component_root_key(self):
return "some-component"
class MockSecretStrategy(SecretDiscoveryStrategy):
def __init__(self, global_options):
self.global_options = global_options
@@ -401,13 +417,11 @@ def test_update_paths_in_config_nested_config():
)
# Test the update_paths_in_config method
updated_config = transformer.update_paths_in_config(
source_config, extra_files_discovery, "matrix-authentication-service"
)
updated_config = transformer.update_paths_in_config(source_config, extra_files_discovery)
# Verify paths are updated correctly
assert updated_config["email"]["template_dir"] == "/etc/matrix-authentication-service/extra/templates"
assert updated_config["email"]["config"]["tls_cert"] == "/etc/matrix-authentication-service/extra/cert.pem"
assert updated_config["email"]["template_dir"] == "/etc/some-component/extra/templates"
assert updated_config["email"]["config"]["tls_cert"] == "/etc/some-component/extra/cert.pem"
assert updated_config["email"]["smtp_host"] == "smtp.example.com" # Unchanged
assert updated_config["other_setting"] == "preserved" # Unchanged
@@ -18,7 +18,7 @@ from ess_migration_tool.engine import MigrationEngine
from ess_migration_tool.extra_files import ExtraFilesError
from ess_migration_tool.inputs import InputProcessor
from ess_migration_tool.secrets import SecretsError
from ess_migration_tool.synapse import prompt_for_ingress_host
from ess_migration_tool.synapse import SYNAPSE_STRATEGY_NAME, prompt_for_ingress_host
def test_migration_with_missing_secrets_prompt(
@@ -39,7 +39,7 @@ def test_migration_with_missing_secrets_prompt(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
ess_values = {}
@@ -155,7 +155,7 @@ def test_quiet_mode_fails_on_missing_secrets(tmp_path, synapse_config_with_signi
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
# Create logger in quiet mode (CRITICAL level)
@@ -193,7 +193,7 @@ def test_quiet_mode_fails_on_missing_extra_files(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
# Create logger in quiet mode (CRITICAL level)
@@ -231,7 +231,7 @@ def test_migration_with_unknown_workers_prompt(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
ess_values = {}
@@ -298,7 +298,7 @@ def test_migration_with_missing_extra_files_prompt(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
ess_values = {}
@@ -368,7 +368,7 @@ def test_database_choice_prompt_existing_database(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
log_capture_string = StringIO()
@@ -434,7 +434,7 @@ def test_database_choice_prompt_ess_managed(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
log_capture_string = StringIO()
@@ -500,7 +500,7 @@ def test_database_choice_prompt_default(
input_processor = InputProcessor()
input_processor.load_migration_input(
config_path=str(synapse_config_file),
name="synapse",
name=SYNAPSE_STRATEGY_NAME,
)
log_capture_string = StringIO()
@@ -50,7 +50,7 @@ def test_migration_output_schema_validation(tmp_path, synapse_config_with_signin
# Load migration input
input_processor = InputProcessor()
input_processor.load_migration_input(
name="synapse",
name="Synapse",
config_path=synapse_path,
)