|
| 1 | +# :coding: utf-8 |
| 2 | +# :copyright: Copyright (c) 2024 ftrack |
| 3 | + |
| 4 | +# TODO: make sure that the sources in the metadata (especially for conflicts) are always in the same order |
| 5 | +# TODO: Maybe the configuration can only be in one state at a time |
| 6 | +# it can not contain multiple states at the same time. This will ensure |
| 7 | +# that the configuration is always in a valid state. |
| 8 | +# We'll always clear all successive states when a previous state is changed. |
| 9 | + |
| 10 | +import logging |
| 11 | +import tempfile |
| 12 | + |
| 13 | +from pathlib import Path |
| 14 | +from typing import Self, Optional |
| 15 | + |
| 16 | +from omegaconf import OmegaConf, DictConfig |
| 17 | + |
| 18 | +from .helper.types import ConfigurationSpec |
| 19 | +from .utility.configuration import ( |
| 20 | + get_configuration_specs_from_entrypoint, |
| 21 | + get_configuration_specs_from_namespace, |
| 22 | + get_configuration_specs_from_paths, |
| 23 | + get_configuration_specs_from_files, |
| 24 | + get_conflicts_from_configuration_specs, |
| 25 | + get_configuration_keys_by_pattern, |
| 26 | + create_metadata_from_configuration_specs, |
| 27 | + create_configuration_specs_from_metadata, |
| 28 | + save_configuration_to_yaml, |
| 29 | + convert_configuration_to_dict, |
| 30 | + compose_conflict_keys_in_specific_order_onto_configuration, |
| 31 | + compose_configuration_from_configuration_specs, |
| 32 | + resolve_configuration, |
| 33 | + remove_keys_marked_for_deletion, |
| 34 | + remove_keys_by_full_key, |
| 35 | +) |
| 36 | +from .utility.resolver import register_ft_resolvers |
| 37 | + |
| 38 | +logging.basicConfig(level=logging.INFO) |
| 39 | + |
| 40 | + |
| 41 | +class Configuration: |
| 42 | + """ |
| 43 | + This class wraps the configuration process and provides a simple interface to load, compose and resolve configurations. |
| 44 | + Where feasible, it exposes a fluent interface to chain the configuration steps e.g. |
| 45 | + Configuration().load_from_entrypoint("connect.configuration").compose().resolve().dump("/tmp/configurations") |
| 46 | + """ |
| 47 | + |
| 48 | + def __init__(self): |
| 49 | + # TODO: when we generate the metadata from the specs, we'll always stop on conflicts |
| 50 | + # when metadata is provided by the user, we'll use the CONFLICT_HANDLING |
| 51 | + self._register_constructors_and_resolvers() |
| 52 | + self._specs: set[ConfigurationSpec] = set() |
| 53 | + self._metadata: DictConfig = OmegaConf.create({}) |
| 54 | + self._conflicts: DictConfig = OmegaConf.create({}) |
| 55 | + self._conflict_resolution: DictConfig = OmegaConf.create({}) |
| 56 | + self._composed: DictConfig = OmegaConf.create({}) |
| 57 | + self._resolved: DictConfig = OmegaConf.create({}) |
| 58 | + |
| 59 | + @property |
| 60 | + def metadata(self) -> DictConfig: |
| 61 | + return self._metadata |
| 62 | + |
| 63 | + @property |
| 64 | + def conflicts(self) -> DictConfig: |
| 65 | + return self._conflicts |
| 66 | + |
| 67 | + @property |
| 68 | + def composed(self) -> DictConfig: |
| 69 | + return self._composed |
| 70 | + |
| 71 | + @property |
| 72 | + def resolved(self) -> DictConfig: |
| 73 | + return self._resolved |
| 74 | + |
| 75 | + @staticmethod |
| 76 | + def _register_constructors_and_resolvers() -> None: |
| 77 | + register_ft_resolvers() |
| 78 | + register_ft_resolvers() |
| 79 | + # extend_omegaconf_loader() |
| 80 | + |
| 81 | + def load_from_entrypoint(self, entrypoint: str) -> Self: |
| 82 | + self._specs = self._specs.union( |
| 83 | + get_configuration_specs_from_entrypoint(entrypoint) |
| 84 | + ) |
| 85 | + self._generate_metadata_from_specs() |
| 86 | + return self |
| 87 | + |
| 88 | + def load_from_namespace(self, namespace: str, module_name: str) -> Self: |
| 89 | + self._specs = self._specs.union( |
| 90 | + get_configuration_specs_from_namespace(namespace, module_name) |
| 91 | + ) |
| 92 | + self._generate_metadata_from_specs() |
| 93 | + return self |
| 94 | + |
| 95 | + def load_from_paths(self, paths: list[Path]) -> Self: |
| 96 | + self._specs = self._specs.union(get_configuration_specs_from_paths(paths)) |
| 97 | + self._generate_metadata_from_specs() |
| 98 | + return self |
| 99 | + |
| 100 | + def load_from_files(self, files: list[Path]) -> Self: |
| 101 | + self._specs = self._specs.union(get_configuration_specs_from_files(files)) |
| 102 | + self._generate_metadata_from_specs() |
| 103 | + return self |
| 104 | + |
| 105 | + def load_from_metadata_file(self, path: Path) -> Self: |
| 106 | + loaded_metadata = OmegaConf.load(path) |
| 107 | + specs = create_configuration_specs_from_metadata(loaded_metadata["_metadata"]) |
| 108 | + computed_metadata = create_metadata_from_configuration_specs(specs) |
| 109 | + # TODO: Be more specific in the handling of this case. |
| 110 | + assert ( |
| 111 | + loaded_metadata == computed_metadata |
| 112 | + ), "The loaded metadata does not match the generated metadata." |
| 113 | + # TODO: We might want to avoid storing the specs and compute everything directly |
| 114 | + # on-the-fly from the metadata. |
| 115 | + self._specs = specs |
| 116 | + self._metadata = computed_metadata |
| 117 | + return self |
| 118 | + |
| 119 | + def load_conflict_resolution(self, path: Path) -> Self: |
| 120 | + self._conflict_resolution = OmegaConf.load(path) |
| 121 | + return self |
| 122 | + |
| 123 | + def _generate_metadata_from_specs(self) -> Self: |
| 124 | + self._metadata = create_metadata_from_configuration_specs(self._specs) |
| 125 | + return self |
| 126 | + |
| 127 | + def _check_configuration_specs_for_conflicts(self) -> Self: |
| 128 | + self._conflicts["conflicts"] = get_conflicts_from_configuration_specs( |
| 129 | + self._specs, ["configuration"] |
| 130 | + ) |
| 131 | + return self |
| 132 | + |
| 133 | + def clear(self) -> Self: |
| 134 | + self._specs = set() |
| 135 | + self._metadata = OmegaConf.create({}) |
| 136 | + self._composed = OmegaConf.create({}) |
| 137 | + self._resolved = OmegaConf.create({}) |
| 138 | + return self |
| 139 | + |
| 140 | + def compose(self, conflict_resolution_file: Optional[Path] = None) -> Self: |
| 141 | + self._check_configuration_specs_for_conflicts() |
| 142 | + specs = create_configuration_specs_from_metadata(self._metadata["_metadata"]) |
| 143 | + self._composed = compose_configuration_from_configuration_specs(specs) |
| 144 | + if self._conflicts and not conflict_resolution_file: |
| 145 | + pass |
| 146 | + # raise ValueError("Conflicts detected in the configuration.") |
| 147 | + # TODO: We're already creating the specs when loading the metadata from a file. |
| 148 | + # We should be more consistent and either ONLY use the metadata, or ONLY use the specs. |
| 149 | + else: |
| 150 | + conflicts = OmegaConf.load(conflict_resolution_file) |
| 151 | + self._composed = compose_conflict_keys_in_specific_order_onto_configuration( |
| 152 | + self._composed, self._metadata, conflicts |
| 153 | + ) |
| 154 | + return self |
| 155 | + |
| 156 | + def resolve(self, clean=True) -> Self: |
| 157 | + self._resolved = resolve_configuration(self._composed) |
| 158 | + if clean: |
| 159 | + self._resolved = remove_keys_marked_for_deletion(self._resolved) |
| 160 | + metadata_keys = get_configuration_keys_by_pattern( |
| 161 | + self._resolved, r"^.*_metadata$" |
| 162 | + ) |
| 163 | + self._resolved = remove_keys_by_full_key(self._resolved, metadata_keys) |
| 164 | + return self |
| 165 | + |
| 166 | + @staticmethod |
| 167 | + def as_dict(configuration: DictConfig) -> dict: |
| 168 | + return convert_configuration_to_dict(configuration) |
| 169 | + |
| 170 | + @staticmethod |
| 171 | + def to_yaml(configuration, filepath: Path) -> None: |
| 172 | + save_configuration_to_yaml(configuration, filepath) |
| 173 | + |
| 174 | + def dump(self, folder: Path) -> bool: |
| 175 | + """ |
| 176 | + Dumps all configuration steps to the given folder. |
| 177 | +
|
| 178 | + :param folder: The folder to dump the configurations to. |
| 179 | + :return: Success |
| 180 | + """ |
| 181 | + # First check if we have a valid folder and we can write to it. |
| 182 | + folder = Path(folder) |
| 183 | + try: |
| 184 | + with tempfile.TemporaryFile(dir=folder): |
| 185 | + pass |
| 186 | + except Exception: |
| 187 | + logging.error( |
| 188 | + f"{folder} is not a valid folder, can't be written to or does not exist." |
| 189 | + ) |
| 190 | + return False |
| 191 | + |
| 192 | + save_configuration_to_yaml(self._metadata, folder / "metadata.yaml") |
| 193 | + save_configuration_to_yaml(self._conflicts, folder / "conflicts.yaml") |
| 194 | + save_configuration_to_yaml(self._composed, folder / "composed.yaml") |
| 195 | + save_configuration_to_yaml(self._resolved, folder / "resolved.yaml") |
| 196 | + |
| 197 | + return True |
0 commit comments