|
| 1 | +"""HelmValuesConfig class for managing Helm values and secrets.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +from dataclasses import dataclass, field |
| 6 | +from typing import Any, Dict, Optional |
| 7 | + |
| 8 | +import jsonschema |
| 9 | +from jsonschema.exceptions import ValidationError |
| 10 | + |
| 11 | +from helm_values_manager.backends.simple import SimpleValueBackend |
| 12 | +from helm_values_manager.models.path_data import PathData |
| 13 | +from helm_values_manager.models.value import Value |
| 14 | + |
| 15 | + |
| 16 | +@dataclass |
| 17 | +class Deployment: |
| 18 | + """Deployment configuration.""" |
| 19 | + |
| 20 | + name: str |
| 21 | + auth: Dict[str, Any] |
| 22 | + backend: str |
| 23 | + backend_config: Dict[str, Any] = field(default_factory=dict) |
| 24 | + |
| 25 | + def to_dict(self) -> Dict[str, Any]: |
| 26 | + """Convert deployment to dictionary.""" |
| 27 | + return {"backend": self.backend, "auth": self.auth, "backend_config": self.backend_config} |
| 28 | + |
| 29 | + |
| 30 | +class HelmValuesConfig: |
| 31 | + """Configuration manager for Helm values and secrets.""" |
| 32 | + |
| 33 | + def __init__(self): |
| 34 | + """Initialize configuration.""" |
| 35 | + self.version: str = "1.0" |
| 36 | + self.release: str = "" |
| 37 | + self.deployments: Dict[str, Deployment] = {} |
| 38 | + self._path_map: Dict[str, PathData] = {} |
| 39 | + self._backend = SimpleValueBackend() # For non-sensitive values |
| 40 | + self.default_environment = "default" |
| 41 | + |
| 42 | + @classmethod |
| 43 | + def _load_schema(cls) -> Dict[str, Any]: |
| 44 | + """Load the JSON schema for configuration validation.""" |
| 45 | + schema_path = os.path.join(os.path.dirname(__file__), "..", "schemas", "v1.json") |
| 46 | + with open(schema_path, "r", encoding="utf-8") as f: |
| 47 | + return json.load(f) |
| 48 | + |
| 49 | + def add_config_path( |
| 50 | + self, path: str, description: Optional[str] = None, required: bool = False, sensitive: bool = False |
| 51 | + ) -> None: |
| 52 | + """ |
| 53 | + Add a new configuration path. |
| 54 | +
|
| 55 | + Args: |
| 56 | + path: The configuration path |
| 57 | + description: Description of what this configuration does |
| 58 | + required: Whether this configuration is required |
| 59 | + sensitive: Whether this configuration contains sensitive data |
| 60 | + """ |
| 61 | + if path in self._path_map: |
| 62 | + raise ValueError(f"Path {path} already exists") |
| 63 | + |
| 64 | + metadata = { |
| 65 | + "description": description, |
| 66 | + "required": required, |
| 67 | + "sensitive": sensitive, |
| 68 | + } |
| 69 | + path_data = PathData(path, metadata) |
| 70 | + self._path_map[path] = path_data |
| 71 | + |
| 72 | + def get_value(self, path: str, environment: str, resolve: bool = False) -> str: |
| 73 | + """ |
| 74 | + Get a value for the given path and environment. |
| 75 | +
|
| 76 | + Args: |
| 77 | + path: The configuration path |
| 78 | + environment: The environment name |
| 79 | + resolve: If True, resolve any secret references to their actual values. |
| 80 | + If False, return the raw value which may be a secret reference. |
| 81 | +
|
| 82 | + Returns: |
| 83 | + str: The value (resolved or raw depending on resolve parameter) |
| 84 | +
|
| 85 | + Raises: |
| 86 | + KeyError: If path doesn't exist |
| 87 | + ValueError: If value doesn't exist for the given environment |
| 88 | + """ |
| 89 | + if path not in self._path_map: |
| 90 | + raise KeyError(f"Path {path} not found") |
| 91 | + |
| 92 | + path_data = self._path_map[path] |
| 93 | + value_obj = path_data.get_value(environment) |
| 94 | + if value_obj is None: |
| 95 | + raise ValueError(f"No value found for path {path} in environment {environment}") |
| 96 | + |
| 97 | + value = value_obj.get(resolve=resolve) |
| 98 | + if value is None: |
| 99 | + raise ValueError(f"No value found for path {path} in environment {environment}") |
| 100 | + |
| 101 | + return value |
| 102 | + |
| 103 | + def set_value(self, path: str, environment: str, value: str) -> None: |
| 104 | + """Set a value for the given path and environment.""" |
| 105 | + if path not in self._path_map: |
| 106 | + raise KeyError(f"Path {path} not found") |
| 107 | + |
| 108 | + value_obj = Value(path=path, environment=environment, _backend=self._backend) |
| 109 | + value_obj.set(value) |
| 110 | + self._path_map[path].set_value(environment, value_obj) |
| 111 | + |
| 112 | + def validate(self) -> None: |
| 113 | + """Validate the configuration.""" |
| 114 | + for path_data in self._path_map.values(): |
| 115 | + path_data.validate() |
| 116 | + |
| 117 | + def to_dict(self) -> Dict[str, Any]: |
| 118 | + """Convert the configuration to a dictionary.""" |
| 119 | + return { |
| 120 | + "version": self.version, |
| 121 | + "release": self.release, |
| 122 | + "deployments": {name: depl.to_dict() for name, depl in self.deployments.items()}, |
| 123 | + "config": [path_data.to_dict() for path_data in self._path_map.values()], |
| 124 | + } |
| 125 | + |
| 126 | + @classmethod |
| 127 | + def from_dict(cls, data: dict) -> "HelmValuesConfig": |
| 128 | + """ |
| 129 | + Create a configuration from a dictionary. |
| 130 | +
|
| 131 | + Args: |
| 132 | + data: Dictionary containing configuration data |
| 133 | +
|
| 134 | + Returns: |
| 135 | + HelmValuesConfig: New configuration instance |
| 136 | +
|
| 137 | + Raises: |
| 138 | + ValidationError: If the configuration data is invalid |
| 139 | + """ |
| 140 | + # Convert string boolean values to actual booleans for backward compatibility |
| 141 | + data = data.copy() # Don't modify the input |
| 142 | + for config_item in data.get("config", []): |
| 143 | + for boolean_field in ["required", "sensitive"]: |
| 144 | + if boolean_field in config_item and isinstance(config_item[boolean_field], str): |
| 145 | + config_item[boolean_field] = config_item[boolean_field].lower() == "true" |
| 146 | + |
| 147 | + # Validate against schema |
| 148 | + schema = cls._load_schema() |
| 149 | + try: |
| 150 | + jsonschema.validate(instance=data, schema=schema) |
| 151 | + except ValidationError as e: |
| 152 | + raise e |
| 153 | + |
| 154 | + config = cls() |
| 155 | + config.version = data["version"] |
| 156 | + config.release = data["release"] |
| 157 | + |
| 158 | + # Load deployments |
| 159 | + for name, depl_data in data.get("deployments", {}).items(): |
| 160 | + config.deployments[name] = Deployment( |
| 161 | + name=name, |
| 162 | + backend=depl_data["backend"], |
| 163 | + auth=depl_data["auth"], |
| 164 | + backend_config=depl_data.get("backend_config", {}), |
| 165 | + ) |
| 166 | + |
| 167 | + # Load config paths |
| 168 | + for config_item in data.get("config", []): |
| 169 | + path = config_item["path"] |
| 170 | + metadata = { |
| 171 | + "description": config_item.get("description"), |
| 172 | + "required": config_item.get("required", False), |
| 173 | + "sensitive": config_item.get("sensitive", False), |
| 174 | + } |
| 175 | + path_data = PathData(path, metadata) |
| 176 | + config._path_map[path] = path_data |
| 177 | + |
| 178 | + # Load values |
| 179 | + for env, value in config_item.get("values", {}).items(): |
| 180 | + value_obj = Value(path=path, environment=env, _backend=config._backend) |
| 181 | + value_obj.set(value) |
| 182 | + path_data.set_value(env, value_obj) |
| 183 | + |
| 184 | + return config |
0 commit comments