diff --git a/packages/ess-migration-tool/src/ess_migration_tool/mas.py b/packages/ess-migration-tool/src/ess_migration_tool/mas.py index ed756c2f..9372a168 100644 --- a/packages/ess-migration-tool/src/ess_migration_tool/mas.py +++ b/packages/ess-migration-tool/src/ess_migration_tool/mas.py @@ -13,7 +13,7 @@ import urllib from typing import Any from .interfaces import ExtraFilesDiscoveryStrategy, SecretDiscoveryStrategy -from .migration import MigrationStrategy, TransformationSpec +from .migration import 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 @@ -67,12 +67,13 @@ def parse_postgres_uri(uri: str) -> dict[str, Any]: return {} -def extract_port_from_uri(_, uri: str) -> int | None: +def extract_port_from_uri(_, uri: str, **kwargs: Any) -> int | None: """ Extract port from PostgreSQL URI, returning None if not present. Args: uri: PostgreSQL connection URI + **kwargs: Optional context parameters (unused) Returns: Port as integer if present, None otherwise @@ -82,7 +83,9 @@ def extract_port_from_uri(_, uri: str) -> int | None: return int(port) if port is not None else None -def filter_mas_listeners(pretty_logger: logging.Logger, listeners: list[dict] | None) -> dict[str, Any] | None: +def filter_mas_listeners( + pretty_logger: logging.Logger, listeners: list[dict] | None, **kwargs: Any +) -> dict[str, Any] | None: """ Filter out listeners that are managed by the ESS chart for MAS. @@ -93,6 +96,7 @@ def filter_mas_listeners(pretty_logger: logging.Logger, listeners: list[dict] | Args: pretty_logger: Logger for user-friendly output listeners: List of listener configurations from source MAS config + **kwargs: Optional context parameters (unused) Returns: Dictionary with listeners.yml config structure, or None if no custom listeners remain @@ -233,6 +237,12 @@ class MASMigration(MigrationStrategy): transformer=filter_mas_listeners, required=False, ), # Filter out chart-managed listeners and output to additional config + TransformationSpec( + src_key=".", + target_key="matrixAuthenticationService.additional", + transformer=additional_config_transformer, + required=False, + ), # Generic additional config generation # ... other non-database transformations ... ] @@ -242,7 +252,7 @@ class MASMigration(MigrationStrategy): TransformationSpec( src_key="database.uri", target_key="matrixAuthenticationService.postgres.host", - transformer=lambda _, uri: parse_postgres_uri(uri).get("host"), + transformer=lambda _, uri, **kw: parse_postgres_uri(uri).get("host"), required=True, ), TransformationSpec( @@ -254,19 +264,19 @@ class MASMigration(MigrationStrategy): TransformationSpec( src_key="database.uri", target_key="matrixAuthenticationService.postgres.user", - transformer=lambda _, uri: parse_postgres_uri(uri).get("user"), + transformer=lambda _, uri, **kw: parse_postgres_uri(uri).get("user"), required=True, ), TransformationSpec( src_key="database.uri", target_key="matrixAuthenticationService.postgres.database", - transformer=lambda _, uri: parse_postgres_uri(uri).get("name"), + transformer=lambda _, uri, **kw: parse_postgres_uri(uri).get("name"), required=True, ), TransformationSpec( src_key="database.uri", target_key="matrixAuthenticationService.postgres.sslMode", - transformer=lambda _, uri: parse_postgres_uri(uri).get("ssl"), + transformer=lambda _, uri, **kw: parse_postgres_uri(uri).get("ssl"), required=False, ), # ... other database property transformations ... @@ -277,7 +287,7 @@ class MASMigration(MigrationStrategy): TransformationSpec( src_key="database", # Trigger on database section target_key="postgres.enabled", - transformer=lambda _, __: True, # Set to True for ESS-managed Postgres + transformer=lambda _, __, **kw: True, # Set to True for ESS-managed Postgres ) ] @@ -306,7 +316,7 @@ class MASSecretDiscovery(SecretDiscoveryStrategy): description="MAS database password", config_inline="database.uri", config_path=None, - transformer=lambda uri: parse_postgres_uri(uri).get("password"), + transformer=lambda uri, **kw: parse_postgres_uri(uri).get("password"), ) # Other MAS secrets (always included) diff --git a/packages/ess-migration-tool/src/ess_migration_tool/migration.py b/packages/ess-migration-tool/src/ess_migration_tool/migration.py index a3dcc32d..fdfc54a4 100644 --- a/packages/ess-migration-tool/src/ess_migration_tool/migration.py +++ b/packages/ess-migration-tool/src/ess_migration_tool/migration.py @@ -35,6 +35,51 @@ from .utils import ( logger = logging.getLogger("migration") +def additional_config_transformer( + logger: logging.Logger, + value: Any, + **kwargs: Any, +) -> dict[str, Any]: + """ + Generic transformer for additional config generation. + + All transformers accept **kwargs. This one uses: + - config_to_ess_transformer: ConfigValueTransformer from kwargs + - component_root_key: str from kwargs + - extra_files_discovery: ExtraFilesDiscovery | None from kwargs + """ + source_config = value # value is the source config (when src_key=".") + config_to_ess_transformer = kwargs["config_to_ess_transformer"] + component_root_key = kwargs["component_root_key"] + extra_files_discovery = kwargs.get("extra_files_discovery") + + filtered_config = copy.deepcopy(source_config) + + # Filter out values already processed by other transformations + for source_path in config_to_ess_transformer.tracked_values: + remove_nested_value(filtered_config, source_path) + + # Update file paths if extra files were discovered + if extra_files_discovery: + filtered_config = config_to_ess_transformer.update_paths_in_config( + filtered_config, extra_files_discovery, component_root_key + ) + + # Return in the expected additional config format + # Also preserve any existing entries in additional (like listeners.yml from other transformers) + if filtered_config: + # Check if there are existing entries in the component's additional section + component_config = config_to_ess_transformer.ess_config.get(component_root_key, {}) + existing_additional = component_config.get("additional", {}) + + result = {"00-imported.yaml": {"config": yaml_dump_with_pipe_for_multiline(filtered_config)}} + + # Merge with existing entries - existing entries take precedence + # This preserves listeners.yml, etc. added by other transformers + merged = {**result, **existing_additional} + return merged + return {} + @dataclass class TransformationResult: @@ -61,13 +106,21 @@ class ConfigValueTransformer: 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 - def transform_from_config(self, source_config: dict[str, Any], transformations: list[TransformationSpec]) -> None: + def transform_from_config( + self, + source_config: dict[str, Any], + transformations: list[TransformationSpec], + component_root_key: str = "", + extra_files_discovery: ExtraFilesDiscovery | None = None, + ) -> None: """ Transform values from a source configuration using explicit source and target path mappings. 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 """ for transformation in transformations: # Get the value from the source configuration @@ -77,7 +130,14 @@ class ConfigValueTransformer: if transformation.transformer is not None: # If transformer is provided, always call it (even if value is None) # This allows transformers to handle missing values (e.g., by prompting for input) - transformed_value = transformation.transformer(self.pretty_logger, value) + # Pass context using named kwargs - all transformers now accept **kwargs + transformed_value = transformation.transformer( + self.pretty_logger, + value, + config_to_ess_transformer=self, + component_root_key=component_root_key, + extra_files_discovery=extra_files_discovery, + ) else: # No transformer provided, use the raw value transformed_value = value @@ -423,8 +483,25 @@ class MigrationService: self.ess_config.setdefault(self.component_root_key, {})["enabled"] = True config_to_ess_transformer = ConfigValueTransformer(self.pretty_logger, self.ess_config) + + # Add skipped paths from extra files discovery to tracked_values before transformation + # This ensures they are filtered out by the additional_config_transformer + for discovered_path in extra_files_discovery.discovered_file_paths: + if discovered_path.skipped_reason: + config_to_ess_transformer.tracked_values.append(discovered_path.config_key) + + # Add secret config keys to tracked_values before transformation + # This ensures they are filtered out by the additional_config_transformer + for discover_secret in secret_discovery.discovered_secrets.values(): + config_to_ess_transformer.tracked_values.append(discover_secret.config_key) + # Step 4: Apply component transformations - config_to_ess_transformer.transform_from_config(self.input.config, self.migration.transformations) + 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 5: Handle secrets for the component using the transformer's method # This will update the root ESS config directly and create Kubernetes Secrets @@ -434,7 +511,7 @@ class MigrationService: self.secrets, ) - # Step 6: Handle extra files mounts for the component using the transformer's method + # Step 5: 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, @@ -442,13 +519,16 @@ class MigrationService: self.configmaps, ) + # Step 6: Apply component transformations + 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: Add filtered additional configurations - config_to_ess_transformer.add_additional_config_to_component( - self.component_root_key, self.input.config, extra_files_discovery - ) - - # Step 9: Store results + # Step 8: Store results self.results.extend(config_to_ess_transformer.results) diff --git a/packages/ess-migration-tool/src/ess_migration_tool/models.py b/packages/ess-migration-tool/src/ess_migration_tool/models.py index f97bdbf4..e2b775a2 100644 --- a/packages/ess-migration-tool/src/ess_migration_tool/models.py +++ b/packages/ess-migration-tool/src/ess_migration_tool/models.py @@ -7,7 +7,6 @@ Data models for the migration script using Python dataclasses. """ -import logging from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path @@ -70,7 +69,7 @@ class TransformationSpec: src_key: str # Source configuration path target_key: str # Target ESS configuration path required: bool = True # Whether this transformation is required - transformer: Callable[[logging.Logger, Any], Any] | None = None # Optional transformation function + transformer: Callable[..., Any] | None = None # Optional transformation function @dataclass diff --git a/packages/ess-migration-tool/src/ess_migration_tool/synapse.py b/packages/ess-migration-tool/src/ess_migration_tool/synapse.py index 630a54da..08e88d82 100644 --- a/packages/ess-migration-tool/src/ess_migration_tool/synapse.py +++ b/packages/ess-migration-tool/src/ess_migration_tool/synapse.py @@ -14,7 +14,7 @@ from typing import Any from rapidfuzz import fuzz, process from .interfaces import ExtraFilesDiscoveryStrategy, SecretDiscoveryStrategy -from .migration import MigrationStrategy, TransformationSpec +from .migration import MigrationStrategy, TransformationSpec, additional_config_transformer from .models import DiscoveredSecret, GlobalOptions, MigrationError, SecretConfig from .utils import extract_hostname_from_url, yaml_dump_with_pipe_for_multiline @@ -83,7 +83,7 @@ def prompt_user_for_worker( def extract_workers_from_instance_map( - pretty_logger: logging.Logger, instance_map: dict[str, Any] | None + pretty_logger: logging.Logger, instance_map: dict[str, Any] | None, **kwargs: Any ) -> dict[str, Any] | None: """Extract workers from the instance map.""" @@ -112,7 +112,7 @@ def extract_workers_from_instance_map( return selected_workers -def extract_database_name(pretty_logger: logging.Logger, database_args: dict[str, Any]) -> str: +def extract_database_name(pretty_logger: logging.Logger, database_args: dict[str, Any], **kwargs: Any) -> str: """Extract database name from the database arguments.""" database_name = database_args.get("dbname") if not database_name: @@ -123,13 +123,14 @@ def extract_database_name(pretty_logger: logging.Logger, database_args: dict[str return database_name -def prompt_for_ingress_host(pretty_logger: logging.Logger, public_baseurl: str | None) -> str: +def prompt_for_ingress_host(pretty_logger: logging.Logger, public_baseurl: str | None, **kwargs: Any) -> str: """ Prompt user for ingress host when public_baseurl is missing. Args: pretty_logger: Logger for user-friendly output public_baseurl: The public base URL from source config (may be None or empty) + **kwargs: Optional context parameters (unused) Returns: The ingress host (hostname extracted from public_baseurl or user input) @@ -161,7 +162,9 @@ def prompt_for_ingress_host(pretty_logger: logging.Logger, public_baseurl: str | raise MigrationError("End of input reached during ingress host prompt") from err -def filter_listeners(pretty_logger: logging.Logger, listeners: list[dict] | None) -> dict[str, Any] | None: +def filter_listeners( + pretty_logger: logging.Logger, listeners: list[dict] | None, **kwargs: Any +) -> dict[str, Any] | None: """ Filter out listeners that are managed by the ESS chart. @@ -172,6 +175,7 @@ def filter_listeners(pretty_logger: logging.Logger, listeners: list[dict] | None Args: pretty_logger: Logger for user-friendly output listeners: List of listener configurations from source Synapse config + **kwargs: Optional context parameters (unused) Returns: Dictionary with listeners.yml config structure, or None if no custom listeners remain @@ -304,6 +308,12 @@ class SynapseMigration(MigrationStrategy): transformer=filter_listeners, required=False, ), # Filter out chart-managed listeners and output to additional config + TransformationSpec( + src_key=".", + target_key="synapse.additional", + transformer=additional_config_transformer, + required=False, + ), # Generic additional config generation # ... other non-database transformations ... ] @@ -327,7 +337,7 @@ class SynapseMigration(MigrationStrategy): TransformationSpec( src_key="database", # Trigger on database section target_key="postgres.enabled", - transformer=lambda _, __: True, # Set to True for ESS-managed Postgres + transformer=lambda _, __, **kw: True, # Set to True for ESS-managed Postgres ) ] diff --git a/packages/ess-migration-tool/src/ess_migration_tool/utils.py b/packages/ess-migration-tool/src/ess_migration_tool/utils.py index 462d754e..42174502 100644 --- a/packages/ess-migration-tool/src/ess_migration_tool/utils.py +++ b/packages/ess-migration-tool/src/ess_migration_tool/utils.py @@ -96,13 +96,12 @@ def get_nested_value(config: dict[str, Any], path: str) -> Any: Args: config: Configuration dictionary - path: Dot-separated path to the value. Empty string returns entire config. + path: Dot-separated path to the value. Single dot "." returns entire config. Returns: The value at the specified path, or None if not found """ - if not path: - # Empty path returns the entire config + if path == ".": return config if "." in path: # Nested path @@ -167,12 +166,13 @@ def remove_nested_value(config: dict[str, Any], path: str) -> None: del config[path] -def extract_hostname_from_url(_, url: str) -> str: +def extract_hostname_from_url(_, url: str, **kwargs: Any) -> str: """ Extract hostname from a URL string. Args: url: URL string to parse + **kwargs: Optional context parameters (unused) Returns: Hostname as string if successful, None otherwise