-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema.py
More file actions
383 lines (313 loc) · 13.3 KB
/
schema.py
File metadata and controls
383 lines (313 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""
Config Schema Validation for Fleet Config Manager.
Provides JSON Schema-like validation for fleet and agent configs,
including type checking, required fields, port conflicts, and path validation.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Any
@dataclass
class ValidationError:
"""Represents a single validation error."""
path: str
message: str
severity: str = "error" # "error" | "warning"
def __str__(self) -> str:
return f"[{self.severity.upper()}] {self.path}: {self.message}"
@dataclass
class ValidationResult:
"""Result of a config validation pass."""
valid: bool = True
errors: list[ValidationError] = field(default_factory=list)
def add_error(self, path: str, message: str, severity: str = "error") -> None:
self.errors.append(ValidationError(path=path, message=message, severity=severity))
if severity == "error":
self.valid = False
def merge(self, other: ValidationResult) -> None:
self.errors.extend(other.errors)
if not other.valid:
self.valid = False
def __str__(self) -> str:
if not self.errors:
return "Config is valid."
lines = [f"Found {len(self.errors)} issue(s):"]
for err in self.errors:
lines.append(f" {err}")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Field definitions
# ---------------------------------------------------------------------------
FIELD_TYPES: dict[str, type | tuple[type, ...]] = {
"str": str,
"int": int,
"float": (int, float),
"bool": bool,
"dict": dict,
"list": list,
"any": object,
}
from typing import Callable
@dataclass
class FieldSpec:
"""Specification for a single config field."""
name: str
field_type: str = "any"
required: bool = False
default: Any = None
default_factory: Callable[..., Any] | None = None
min_val: int | float | None = None
max_val: int | float | None = None
pattern: str | None = None
description: str = ""
def get_default(self) -> Any:
if self.default_factory is not None:
return self.default_factory()
return self.default
def validate_type(self, value: Any) -> bool:
expected = FIELD_TYPES.get(self.field_type, object)
if isinstance(expected, tuple):
return isinstance(value, expected)
return isinstance(value, expected) or value is None
def validate_range(self, value: Any) -> bool:
if isinstance(value, (int, float)):
if self.min_val is not None and value < self.min_val:
return False
if self.max_val is not None and value > self.max_val:
return False
return True
# ---------------------------------------------------------------------------
# Fleet config schema
# ---------------------------------------------------------------------------
FLEET_FIELDS: list[FieldSpec] = [
FieldSpec("fleet_name", "str", required=True,
description="Unique name for the fleet instance"),
FieldSpec("version", "str", default="1.0.0",
description="Fleet configuration version"),
FieldSpec("environment", "str", default="development",
pattern=r"^(development|staging|production|test)$",
description="Deployment environment"),
FieldSpec("keeper", "dict", required=True,
description="Fleet Keeper agent configuration"),
FieldSpec("agents", "dict", default_factory=dict,
description="Per-agent configurations"),
FieldSpec("network", "dict", default_factory=dict,
description="Network topology settings"),
FieldSpec("logging", "dict", default_factory=dict,
description="Logging configuration"),
FieldSpec("secrets", "dict", default_factory=dict,
description="Secret keys and tokens"),
]
KEEPER_FIELDS: list[FieldSpec] = [
FieldSpec("host", "str", default="127.0.0.1"),
FieldSpec("port", "int", default=8000, min_val=1, max_val=65535),
FieldSpec("workers", "int", default=4, min_val=1, max_val=32),
FieldSpec("heartbeat_interval", "int", default=30, min_val=5),
FieldSpec("max_agents", "int", default=50, min_val=1),
]
NETWORK_FIELDS: list[FieldSpec] = [
FieldSpec("default_host", "str", default="127.0.0.1"),
FieldSpec("base_port", "int", default=9000, min_val=1, max_val=65535),
FieldSpec("port_step", "int", default=100, min_val=1, max_val=1000),
FieldSpec("allowed_hosts", "list", default_factory=list),
FieldSpec("tls_enabled", "bool", default=False),
]
LOGGING_FIELDS: list[FieldSpec] = [
FieldSpec("level", "str", default="INFO",
pattern=r"^(DEBUG|INFO|WARNING|ERROR|CRITICAL)$"),
FieldSpec("format", "str", default="json"),
FieldSpec("file", "str", default=None),
FieldSpec("max_size_mb", "int", default=100, min_val=1),
]
AGENT_FIELDS: list[FieldSpec] = [
FieldSpec("name", "str", required=True),
FieldSpec("type", "str", required=True),
FieldSpec("host", "str", default="127.0.0.1"),
FieldSpec("port", "int", default=9000, min_val=1, max_val=65535),
FieldSpec("enabled", "bool", default=True),
FieldSpec("config_path", "str", default=None),
FieldSpec("env", "dict", default_factory=dict),
FieldSpec("secrets", "dict", default_factory=dict),
]
# ---------------------------------------------------------------------------
# ConfigSchema validator
# ---------------------------------------------------------------------------
class ConfigSchema:
"""JSON Schema-like validation for fleet configs.
Validates fleet config, agent config, network topology, port conflicts,
and path existence checking.
"""
def __init__(self, strict: bool = False) -> None:
self.strict = strict
# -- Fleet-level validation -----------------------------------------------
def validate_fleet(self, config: dict[str, Any]) -> ValidationResult:
"""Validate a complete fleet configuration."""
result = ValidationResult()
for spec in FLEET_FIELDS:
self._validate_field(config, spec, result)
# Validate nested keeper section
keeper = config.get("keeper", {})
if isinstance(keeper, dict):
keeper_result = self._validate_section(keeper, KEEPER_FIELDS, "keeper")
result.merge(keeper_result)
# Validate nested network section
network = config.get("network", {})
if isinstance(network, dict):
net_result = self._validate_section(network, NETWORK_FIELDS, "network")
result.merge(net_result)
# Validate nested logging section
logging = config.get("logging", {})
if isinstance(logging, dict):
log_result = self._validate_section(logging, LOGGING_FIELDS, "logging")
result.merge(log_result)
# Validate agents
agents = config.get("agents", {})
if isinstance(agents, dict):
for agent_name, agent_cfg in agents.items():
agent_result = self.validate_agent(agent_cfg, path=f"agents.{agent_name}")
result.merge(agent_result)
# Cross-cutting checks
self._check_port_conflicts(config, result)
self._check_path_existence(config, result)
return result
# -- Agent-level validation -----------------------------------------------
def validate_agent(
self, config: dict[str, Any], path: str = ""
) -> ValidationResult:
"""Validate a single agent configuration."""
result = ValidationResult()
for spec in AGENT_FIELDS:
self._validate_field(config, spec, result, parent=path)
return result
# -- Network topology validation ------------------------------------------
def validate_network_topology(
self, config: dict[str, Any]
) -> ValidationResult:
"""Validate network topology for consistency."""
result = ValidationResult()
network = config.get("network", {})
if not isinstance(network, dict):
result.add_error("network", "network section must be a dictionary")
return result
base_port = network.get("base_port", 9000)
port_step = network.get("port_step", 100)
agents = config.get("agents", {})
assigned_ports: list[int] = []
if isinstance(agents, dict):
for agent_name, agent_cfg in agents.items():
if not isinstance(agent_cfg, dict):
continue
port = agent_cfg.get("port")
if isinstance(port, int):
assigned_ports.append(port)
keeper = config.get("keeper", {})
if isinstance(keeper, dict) and isinstance(keeper.get("port"), int):
assigned_ports.append(keeper["port"])
# Check for port overlaps
seen: set[int] = set()
for port in assigned_ports:
if port in seen:
result.add_error("network.ports", f"Duplicate port detected: {port}")
seen.add(port)
# Warn if ports are far from base_port
if assigned_ports:
max_expected = base_port + port_step * 20 # reasonable upper bound
for port in assigned_ports:
if port > max_expected:
result.add_error(
f"network.ports",
f"Port {port} is well beyond base_port {base_port} "
f"with step {port_step}",
severity="warning",
)
return result
# -- Port conflict detection ----------------------------------------------
def _check_port_conflicts(
self, config: dict[str, Any], result: ValidationResult
) -> None:
"""Detect port conflicts across all agents and keeper."""
port_map: dict[int, str] = {}
keeper = config.get("keeper", {})
if isinstance(keeper, dict):
keeper_port = keeper.get("port")
if isinstance(keeper_port, int):
port_map[keeper_port] = "keeper"
agents = config.get("agents", {})
if isinstance(agents, dict):
for agent_name, agent_cfg in agents.items():
if not isinstance(agent_cfg, dict):
continue
port = agent_cfg.get("port")
if isinstance(port, int):
if port in port_map:
result.add_error(
f"agents.{agent_name}.port",
f"Port {port} conflicts with {port_map[port]}",
)
else:
port_map[port] = f"agents.{agent_name}"
# -- Path existence checking ----------------------------------------------
def _check_path_existence(
self, config: dict[str, Any], result: ValidationResult
) -> None:
"""Check that referenced paths exist on disk."""
path_keys = [
("logging.file", config.get("logging", {}).get("file") if isinstance(config.get("logging"), dict) else None),
]
agents = config.get("agents", {})
if isinstance(agents, dict):
for agent_name, agent_cfg in agents.items():
if not isinstance(agent_cfg, dict):
continue
cfg_path = agent_cfg.get("config_path")
if cfg_path:
path_keys.append((f"agents.{agent_name}.config_path", cfg_path))
for path_str, val in path_keys:
if isinstance(val, str) and val and not os.path.exists(val):
severity = "warning"
result.add_error(path_str, f"Path does not exist: {val}", severity=severity)
# -- Internal helpers -----------------------------------------------------
def _validate_field(
self,
config: dict[str, Any],
spec: FieldSpec,
result: ValidationResult,
parent: str = "",
) -> None:
"""Validate a single field against its spec."""
full_path = f"{parent}.{spec.name}" if parent else spec.name
value = config.get(spec.name)
if value is None:
if spec.required:
result.add_error(full_path, f"Required field missing: {spec.name}")
return
if not spec.validate_type(value):
result.add_error(
full_path,
f"Expected type {spec.field_type}, got {type(value).__name__}",
)
return
if not spec.validate_range(value):
result.add_error(
full_path,
f"Value {value} out of range "
f"[{spec.min_val}, {spec.max_val}]",
)
if spec.pattern and isinstance(value, str):
import re
if not re.match(spec.pattern, value):
result.add_error(
full_path,
f"Value '{value}' does not match pattern '{spec.pattern}'",
)
def _validate_section(
self,
section: dict[str, Any],
fields: list[FieldSpec],
prefix: str,
) -> ValidationResult:
"""Validate a nested section of config."""
result = ValidationResult()
for spec in fields:
self._validate_field(section, spec, result, parent=prefix)
return result