|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +""" |
| 3 | +LMCache Controller Configuration |
| 4 | +
|
| 5 | +Configuration system for LMCache Controller that: |
| 6 | +- Loads configuration from YAML file or environment variables |
| 7 | +- Supports command-line parameter overrides |
| 8 | +- Provides thread-safe singleton pattern for global access |
| 9 | +""" |
| 10 | + |
| 11 | +# Standard |
| 12 | +from typing import Any, Dict, Optional |
| 13 | +import json |
| 14 | + |
| 15 | +# First Party |
| 16 | +from lmcache.logging import init_logger |
| 17 | +from lmcache.v1.config_base import ( |
| 18 | + create_config_class, |
| 19 | + create_singleton_config, |
| 20 | + load_config_with_overrides, |
| 21 | +) |
| 22 | + |
| 23 | +logger = init_logger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +# Controller-specific configuration definitions |
| 27 | +_CONTROLLER_CONFIG_DEFINITIONS: dict[str, dict[str, Any]] = { |
| 28 | + # Basic controller configurations |
| 29 | + "controller_monitor_ports": { |
| 30 | + "type": Optional[dict], |
| 31 | + "default": '{"pull": 8300, "reply": 8400}', |
| 32 | + "env_converter": lambda x: ( |
| 33 | + x if isinstance(x, dict) else json.loads(x) if x else None |
| 34 | + ), |
| 35 | + "description": "JSON string of monitor ports", |
| 36 | + }, |
| 37 | + "controller_host": { |
| 38 | + "type": str, |
| 39 | + "default": "0.0.0.0", |
| 40 | + "env_converter": str, |
| 41 | + "description": "Controller host address", |
| 42 | + }, |
| 43 | + "controller_port": { |
| 44 | + "type": int, |
| 45 | + "default": 9000, |
| 46 | + "env_converter": int, |
| 47 | + "description": "Controller API server port", |
| 48 | + }, |
| 49 | + "health_check_interval": { |
| 50 | + "type": int, |
| 51 | + "default": -1, |
| 52 | + "env_converter": int, |
| 53 | + "description": "Health check interval in seconds (-1 = disabled)", |
| 54 | + }, |
| 55 | + "lmcache_worker_timeout": { |
| 56 | + "type": int, |
| 57 | + "default": 300, |
| 58 | + "env_converter": int, |
| 59 | + "description": "LMCache worker timeout in seconds", |
| 60 | + }, |
| 61 | + # Extra configurations |
| 62 | + "extra_config": { |
| 63 | + "type": Optional[dict], |
| 64 | + "default": None, |
| 65 | + "env_converter": lambda x: ( |
| 66 | + x if isinstance(x, dict) else json.loads(x) if x else None |
| 67 | + ), |
| 68 | + "description": "Extra configuration parameters", |
| 69 | + }, |
| 70 | +} |
| 71 | + |
| 72 | + |
| 73 | +# Specialized methods that are unique to ControllerConfig |
| 74 | +def _validate_config(self): |
| 75 | + """Validate configuration parameters""" |
| 76 | + # Validate timeouts |
| 77 | + if self.health_check_interval != -1 and self.health_check_interval < 1: |
| 78 | + raise ValueError(f"Invalid health_check_interval: {self.health_check_interval}") |
| 79 | + return self |
| 80 | + |
| 81 | + |
| 82 | +def _log_config(self): |
| 83 | + """Log configuration""" |
| 84 | + config_dict = {} |
| 85 | + for name in _CONTROLLER_CONFIG_DEFINITIONS: |
| 86 | + value = getattr(self, name) |
| 87 | + config_dict[name] = value |
| 88 | + |
| 89 | + logger.info(f"Controller Configuration: {config_dict}") |
| 90 | + return self |
| 91 | + |
| 92 | + |
| 93 | +def _post_init(self): |
| 94 | + """Post-initialization setup""" |
| 95 | + pass |
| 96 | + |
| 97 | + |
| 98 | +# Create configuration class using the base utility |
| 99 | +ControllerConfig = create_config_class( |
| 100 | + config_name="ControllerConfig", |
| 101 | + config_definitions=_CONTROLLER_CONFIG_DEFINITIONS, |
| 102 | + namespace_extras={ |
| 103 | + "validate": _validate_config, |
| 104 | + "log_config": _log_config, |
| 105 | + "__post_init__": _post_init, |
| 106 | + }, |
| 107 | + env_prefix="LMCACHE_CONTROLLER_", |
| 108 | +) |
| 109 | + |
| 110 | + |
| 111 | +# Create singleton getter using the base utility |
| 112 | +controller_get_or_create_config = create_singleton_config( |
| 113 | + getter_func_name="controller_get_or_create_config", |
| 114 | + config_class=ControllerConfig, |
| 115 | + config_env_var="LMCACHE_CONTROLLER_CONFIG_FILE", |
| 116 | +) |
| 117 | + |
| 118 | + |
| 119 | +def override_controller_config_from_dict( |
| 120 | + config: "ControllerConfig", # type: ignore[valid-type] |
| 121 | + overrides: dict[str, Any], |
| 122 | +): |
| 123 | + """Override configuration with dictionary""" |
| 124 | + for key, value in overrides.items(): |
| 125 | + if hasattr(config, key): |
| 126 | + old_value = getattr(config, key) |
| 127 | + |
| 128 | + # Check if this field has an env_converter in the definitions |
| 129 | + if key in _CONTROLLER_CONFIG_DEFINITIONS: |
| 130 | + env_converter = _CONTROLLER_CONFIG_DEFINITIONS[key].get("env_converter") |
| 131 | + if env_converter: |
| 132 | + try: |
| 133 | + # Apply the env_converter to the value |
| 134 | + converted_value = env_converter(value) |
| 135 | + setattr(config, key, converted_value) |
| 136 | + except (ValueError, json.JSONDecodeError) as e: |
| 137 | + logger.warning(f"Failed to convert {key}={value!r}: {e}") |
| 138 | + # Keep the original value if conversion fails |
| 139 | + setattr(config, key, value) |
| 140 | + else: |
| 141 | + setattr(config, key, value) |
| 142 | + else: |
| 143 | + setattr(config, key, value) |
| 144 | + |
| 145 | + new_value = getattr(config, key) |
| 146 | + if old_value != new_value: |
| 147 | + logger.info( |
| 148 | + f"Override controller config: {key} = {new_value} (was {old_value})" |
| 149 | + ) |
| 150 | + else: |
| 151 | + logger.warning(f"Unknown controller config key: {key}, ignoring") |
| 152 | + |
| 153 | + |
| 154 | +def load_controller_config_with_overrides( |
| 155 | + config_file_path: Optional[str] = None, |
| 156 | + overrides: Optional[Dict[str, Any]] = None, |
| 157 | +) -> "ControllerConfig": # type: ignore[valid-type] |
| 158 | + """ |
| 159 | + Load controller configuration with support for file, env vars, and overrides. |
| 160 | +
|
| 161 | + This function uses the generic load_config_with_overrides utility from |
| 162 | + config_base.py to reduce code duplication. |
| 163 | +
|
| 164 | + Args: |
| 165 | + config_file_path: Optional direct path to config file |
| 166 | + overrides: Optional dictionary of configuration overrides |
| 167 | +
|
| 168 | + Returns: |
| 169 | + Loaded and validated ControllerConfig instance |
| 170 | + """ |
| 171 | + return load_config_with_overrides( |
| 172 | + config_class=ControllerConfig, |
| 173 | + config_file_env_var="LMCACHE_CONTROLLER_CONFIG_FILE", |
| 174 | + config_file_path=config_file_path, |
| 175 | + overrides=overrides, |
| 176 | + ) |
0 commit comments