system-runtime-spec 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- system_runtime/__init__.py +22 -0
- system_runtime/_version.py +86 -0
- system_runtime/clock.py +35 -0
- system_runtime/components.py +103 -0
- system_runtime/filesystem.py +168 -0
- system_runtime/health.py +186 -0
- system_runtime/models/__init__.py +20 -0
- system_runtime/models/_sidex.py +274 -0
- system_runtime/models/component.py +134 -0
- system_runtime/models/filesystem.py +39 -0
- system_runtime/models/health.py +172 -0
- system_runtime/models/py.typed +0 -0
- system_runtime/models/value.py +105 -0
- system_runtime/py.typed +0 -0
- system_runtime/snapshot.py +24 -0
- system_runtime/threshold.py +150 -0
- system_runtime_spec-0.1.0.dist-info/METADATA +186 -0
- system_runtime_spec-0.1.0.dist-info/RECORD +21 -0
- system_runtime_spec-0.1.0.dist-info/WHEEL +4 -0
- system_runtime_spec-0.1.0.dist-info/licenses/LICENSE-APACHE +202 -0
- system_runtime_spec-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""System runtime component compatibility, health graphs, and file discovery."""
|
|
2
|
+
|
|
3
|
+
from .clock import current_clock_sample, status_timestamp
|
|
4
|
+
from .components import check_components
|
|
5
|
+
from .filesystem import RuntimeDirectories
|
|
6
|
+
from .health import current_context, evaluate_health
|
|
7
|
+
from .models import component, filesystem, health, value
|
|
8
|
+
from .snapshot import without_origin
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"RuntimeDirectories",
|
|
12
|
+
"status_timestamp",
|
|
13
|
+
"current_clock_sample",
|
|
14
|
+
"check_components",
|
|
15
|
+
"component",
|
|
16
|
+
"current_context",
|
|
17
|
+
"evaluate_health",
|
|
18
|
+
"filesystem",
|
|
19
|
+
"health",
|
|
20
|
+
"value",
|
|
21
|
+
"without_origin",
|
|
22
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Rugix-compatible version ordering and comparator requirements."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from itertools import zip_longest
|
|
6
|
+
|
|
7
|
+
_VERSION = re.compile(
|
|
8
|
+
r"([0-9]+(?:\.[0-9]+)*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?"
|
|
9
|
+
)
|
|
10
|
+
_COMPARATOR = re.compile(r"(==|!=|>=|<=|=|>|<)?\s*(.+)")
|
|
11
|
+
_MAX = 2**64 - 1
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class Version:
|
|
16
|
+
"""Normalized numeric release and ordered prerelease identifiers."""
|
|
17
|
+
|
|
18
|
+
release: tuple[int, ...]
|
|
19
|
+
prerelease: tuple[int | str, ...]
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def parse(cls, text: str) -> "Version":
|
|
23
|
+
match = _VERSION.fullmatch(text.strip())
|
|
24
|
+
if match is None:
|
|
25
|
+
raise ValueError(f"Invalid version: {text!r}")
|
|
26
|
+
release = tuple(int(part.lstrip("0") or "0") for part in match[1].split("."))
|
|
27
|
+
prerelease = tuple(
|
|
28
|
+
int(part.lstrip("0") or "0") if part.isdigit() else part
|
|
29
|
+
for part in (match[2].split(".") if match[2] else [])
|
|
30
|
+
)
|
|
31
|
+
if any(
|
|
32
|
+
part > _MAX for part in (*release, *prerelease) if isinstance(part, int)
|
|
33
|
+
):
|
|
34
|
+
raise ValueError(f"Version number exceeds u64: {text!r}")
|
|
35
|
+
return cls(release, prerelease)
|
|
36
|
+
|
|
37
|
+
def compare(self, other: "Version") -> int:
|
|
38
|
+
for left, right in zip_longest(self.release, other.release, fillvalue=0):
|
|
39
|
+
if left != right:
|
|
40
|
+
return 1 if left > right else -1
|
|
41
|
+
if not self.prerelease or not other.prerelease:
|
|
42
|
+
return (not self.prerelease) - (not other.prerelease)
|
|
43
|
+
for left_id, right_id in zip(self.prerelease, other.prerelease, strict=False):
|
|
44
|
+
if left_id == right_id:
|
|
45
|
+
continue
|
|
46
|
+
if isinstance(left_id, int) != isinstance(right_id, int):
|
|
47
|
+
return -1 if isinstance(left_id, int) else 1
|
|
48
|
+
if isinstance(left_id, int) and isinstance(right_id, int):
|
|
49
|
+
return 1 if left_id > right_id else -1
|
|
50
|
+
if isinstance(left_id, str) and isinstance(right_id, str):
|
|
51
|
+
return 1 if left_id > right_id else -1
|
|
52
|
+
return (len(self.prerelease) > len(other.prerelease)) - (
|
|
53
|
+
len(self.prerelease) < len(other.prerelease)
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_requirement(text: str) -> list[tuple[str, Version]]:
|
|
58
|
+
"""Parse comma-separated comparators, with a single wildcard allowed."""
|
|
59
|
+
if text.strip() == "*":
|
|
60
|
+
return []
|
|
61
|
+
comparators = []
|
|
62
|
+
for part in text.split(","):
|
|
63
|
+
match = _COMPARATOR.fullmatch(part.strip())
|
|
64
|
+
if match is None:
|
|
65
|
+
raise ValueError(f"Invalid version requirement: {text!r}")
|
|
66
|
+
comparators.append((match[1] or "=", Version.parse(match[2])))
|
|
67
|
+
return comparators
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def matches_requirement(
|
|
71
|
+
requirement: list[tuple[str, Version]], version: Version
|
|
72
|
+
) -> bool:
|
|
73
|
+
"""Match all comparators, including prereleases without implicit exclusions."""
|
|
74
|
+
for operator, target in requirement:
|
|
75
|
+
comparison = version.compare(target)
|
|
76
|
+
if not {
|
|
77
|
+
"=": comparison == 0,
|
|
78
|
+
"==": comparison == 0,
|
|
79
|
+
"!=": comparison != 0,
|
|
80
|
+
">": comparison > 0,
|
|
81
|
+
">=": comparison >= 0,
|
|
82
|
+
"<": comparison < 0,
|
|
83
|
+
"<=": comparison <= 0,
|
|
84
|
+
}[operator]:
|
|
85
|
+
return False
|
|
86
|
+
return True
|
system_runtime/clock.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Correlate health observation times with a system's wall clock for display."""
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime, timedelta
|
|
4
|
+
|
|
5
|
+
from .health import current_context
|
|
6
|
+
from .models.health import HealthClockSample, HealthStatus
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def current_clock_sample() -> HealthClockSample:
|
|
10
|
+
"""Sample UTC between two Linux boot-time reads, using their midpoint."""
|
|
11
|
+
context = current_context()
|
|
12
|
+
timestamp = datetime.now(UTC)
|
|
13
|
+
after = current_context().now_ms
|
|
14
|
+
context.now_ms += (after - context.now_ms) // 2
|
|
15
|
+
return HealthClockSample(context=context, timestamp=timestamp)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def status_timestamp(status: HealthStatus, clock: HealthClockSample) -> datetime | None:
|
|
19
|
+
"""Estimate UTC at millisecond precision, independently of freshness checks.
|
|
20
|
+
|
|
21
|
+
Return None for another boot, a future observation, or an unrepresentable time.
|
|
22
|
+
"""
|
|
23
|
+
if (
|
|
24
|
+
status.boot_id != clock.context.boot_id
|
|
25
|
+
or status.observed_at_ms > clock.context.now_ms
|
|
26
|
+
):
|
|
27
|
+
return None
|
|
28
|
+
try:
|
|
29
|
+
timestamp = clock.timestamp.astimezone(UTC)
|
|
30
|
+
timestamp = timestamp.replace(microsecond=timestamp.microsecond // 1000 * 1000)
|
|
31
|
+
return timestamp - timedelta(
|
|
32
|
+
milliseconds=clock.context.now_ms - status.observed_at_ms
|
|
33
|
+
)
|
|
34
|
+
except OverflowError:
|
|
35
|
+
return None
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Evaluate the compatibility of a complete component composition."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
|
|
6
|
+
from ._version import Version, matches_requirement, parse_requirement
|
|
7
|
+
from .models.component import (
|
|
8
|
+
CapabilityDeclaration,
|
|
9
|
+
CapabilitySelectorDeclaration,
|
|
10
|
+
CompatibilityProblem,
|
|
11
|
+
CompatibilityProblem_Conflict,
|
|
12
|
+
CompatibilityProblem_DuplicateClaim,
|
|
13
|
+
CompatibilityProblem_DuplicateComponent,
|
|
14
|
+
CompatibilityProblem_UnsatisfiedRequirement,
|
|
15
|
+
CompatibilityReport,
|
|
16
|
+
ComponentDeclaration,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def check_components(components: Sequence[ComponentDeclaration]) -> CompatibilityReport:
|
|
21
|
+
"""Validate declarations and report every violated composition constraint.
|
|
22
|
+
|
|
23
|
+
Invalid version syntax or simultaneous version and value fields raise ValueError.
|
|
24
|
+
"""
|
|
25
|
+
provided: list[tuple[str, CapabilityDeclaration, Version | None]] = []
|
|
26
|
+
selectors: list[
|
|
27
|
+
tuple[
|
|
28
|
+
str, bool, CapabilitySelectorDeclaration, list[tuple[str, Version]] | None
|
|
29
|
+
]
|
|
30
|
+
] = []
|
|
31
|
+
claims: dict[str, list[str]] = {}
|
|
32
|
+
for component in components:
|
|
33
|
+
implicit = CapabilityDeclaration(id=component.id, version=component.version)
|
|
34
|
+
for capability in [implicit, *(component.provides or [])]:
|
|
35
|
+
_validate(capability)
|
|
36
|
+
version = (
|
|
37
|
+
Version.parse(capability.version)
|
|
38
|
+
if capability.version is not None
|
|
39
|
+
else None
|
|
40
|
+
)
|
|
41
|
+
provided.append((component.id, capability, version))
|
|
42
|
+
for claim in sorted({claim.id for claim in component.claims or []}):
|
|
43
|
+
claims.setdefault(claim, []).append(component.id)
|
|
44
|
+
for conflict, declarations in [
|
|
45
|
+
(False, component.requires),
|
|
46
|
+
(True, component.conflicts),
|
|
47
|
+
]:
|
|
48
|
+
for selector in declarations or []:
|
|
49
|
+
_validate(selector)
|
|
50
|
+
requirement = (
|
|
51
|
+
parse_requirement(selector.version)
|
|
52
|
+
if selector.version is not None
|
|
53
|
+
else None
|
|
54
|
+
)
|
|
55
|
+
selectors.append((component.id, conflict, selector, requirement))
|
|
56
|
+
problems: list[CompatibilityProblem] = [
|
|
57
|
+
CompatibilityProblem_DuplicateComponent(id=id)
|
|
58
|
+
for id, count in sorted(
|
|
59
|
+
Counter(component.id for component in components).items()
|
|
60
|
+
)
|
|
61
|
+
if count > 1
|
|
62
|
+
]
|
|
63
|
+
problems.extend(
|
|
64
|
+
CompatibilityProblem_DuplicateClaim(id=id, components=owners)
|
|
65
|
+
for id, owners in sorted(claims.items())
|
|
66
|
+
if len(owners) > 1
|
|
67
|
+
)
|
|
68
|
+
for component_id, conflict, selector, requirement in selectors:
|
|
69
|
+
matches = [
|
|
70
|
+
(provider, capability)
|
|
71
|
+
for provider, capability, version in provided
|
|
72
|
+
if capability.id == selector.id
|
|
73
|
+
and (selector.value is None or selector.value == capability.value)
|
|
74
|
+
and (
|
|
75
|
+
requirement is None
|
|
76
|
+
or (version is not None and matches_requirement(requirement, version))
|
|
77
|
+
)
|
|
78
|
+
]
|
|
79
|
+
if conflict:
|
|
80
|
+
problems.extend(
|
|
81
|
+
CompatibilityProblem_Conflict(
|
|
82
|
+
component=component_id,
|
|
83
|
+
selector=selector,
|
|
84
|
+
provider=provider,
|
|
85
|
+
capability=capability,
|
|
86
|
+
)
|
|
87
|
+
for provider, capability in matches
|
|
88
|
+
)
|
|
89
|
+
elif not matches:
|
|
90
|
+
problems.append(
|
|
91
|
+
CompatibilityProblem_UnsatisfiedRequirement(
|
|
92
|
+
component=component_id, selector=selector
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
return CompatibilityReport(consistent=not problems, problems=problems)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _validate(
|
|
99
|
+
declaration: CapabilityDeclaration | CapabilitySelectorDeclaration,
|
|
100
|
+
) -> None:
|
|
101
|
+
"""Reject ambiguous capability declarations before matching."""
|
|
102
|
+
if declaration.version is not None and declaration.value is not None:
|
|
103
|
+
raise ValueError(f"Capability {declaration.id!r} has both version and value")
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""Load file contributions from standard and additional Linux directories."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import stat
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import TypeVar
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from .models.component import ComponentDeclaration
|
|
12
|
+
from .models.filesystem import DirectoryConfig, RuntimeSnapshot
|
|
13
|
+
from .models.health import HealthNode, HealthStatus
|
|
14
|
+
from .models.value import ValueDefinition, ValueObservation
|
|
15
|
+
|
|
16
|
+
_PREFIXES = ("/usr/lib/system-runtime", "/etc/system-runtime", "/run/system-runtime")
|
|
17
|
+
Model = TypeVar("Model", bound=BaseModel)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class RuntimeDirectories:
|
|
22
|
+
"""Directory sources, resolved beneath root, with explicit extension support."""
|
|
23
|
+
|
|
24
|
+
root: Path = field(default_factory=lambda: Path("/"))
|
|
25
|
+
components: list[str] = field(default_factory=list)
|
|
26
|
+
health_nodes: list[str] = field(default_factory=list)
|
|
27
|
+
health_statuses: list[str] = field(default_factory=list)
|
|
28
|
+
values: list[str] = field(default_factory=list)
|
|
29
|
+
value_observations: list[str] = field(default_factory=list)
|
|
30
|
+
configuration: list[str] = field(default_factory=list)
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def standard(cls, root: str | Path = "/") -> "RuntimeDirectories":
|
|
34
|
+
return cls(
|
|
35
|
+
root=Path(root),
|
|
36
|
+
components=[f"{prefix}/components" for prefix in _PREFIXES],
|
|
37
|
+
health_nodes=[f"{prefix}/health/nodes" for prefix in _PREFIXES],
|
|
38
|
+
health_statuses=["/run/system-runtime/health/status"],
|
|
39
|
+
values=[f"{prefix}/values/definitions" for prefix in _PREFIXES],
|
|
40
|
+
value_observations=["/run/system-runtime/values/observations"],
|
|
41
|
+
configuration=[f"{prefix}/directories" for prefix in _PREFIXES],
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
def extend(self, config: DirectoryConfig) -> None:
|
|
45
|
+
"""Append directory sources without replacing existing contributions."""
|
|
46
|
+
self.components.extend(config.components or [])
|
|
47
|
+
self.health_nodes.extend(config.health_nodes or [])
|
|
48
|
+
self.health_statuses.extend(config.health_statuses or [])
|
|
49
|
+
self.values.extend(config.values or [])
|
|
50
|
+
self.value_observations.extend(config.value_observations or [])
|
|
51
|
+
|
|
52
|
+
def load(self) -> RuntimeSnapshot:
|
|
53
|
+
"""Reload extension configurations and collect regular JSON files.
|
|
54
|
+
|
|
55
|
+
Whole '*' segments select real directories. Missing roots are ignored.
|
|
56
|
+
An explicit root may be a symlink; nested symlinks are skipped.
|
|
57
|
+
Overlapping sources read each physical file once.
|
|
58
|
+
"""
|
|
59
|
+
effective = RuntimeDirectories(
|
|
60
|
+
root=self.root,
|
|
61
|
+
components=self.components.copy(),
|
|
62
|
+
health_nodes=self.health_nodes.copy(),
|
|
63
|
+
health_statuses=self.health_statuses.copy(),
|
|
64
|
+
values=self.values.copy(),
|
|
65
|
+
value_observations=self.value_observations.copy(),
|
|
66
|
+
)
|
|
67
|
+
for path in self._files(self.configuration):
|
|
68
|
+
effective.extend(_read(path, DirectoryConfig))
|
|
69
|
+
values = [
|
|
70
|
+
_read(path, ValueDefinition) for path in effective._files(effective.values)
|
|
71
|
+
]
|
|
72
|
+
observations = [
|
|
73
|
+
_read(path, ValueObservation)
|
|
74
|
+
for path in effective._files(effective.value_observations)
|
|
75
|
+
]
|
|
76
|
+
return RuntimeSnapshot(
|
|
77
|
+
values=values or None,
|
|
78
|
+
value_observations=observations or None,
|
|
79
|
+
components=[
|
|
80
|
+
_read(path, ComponentDeclaration)
|
|
81
|
+
for path in effective._files(effective.components)
|
|
82
|
+
],
|
|
83
|
+
health_nodes=[
|
|
84
|
+
_read(path, HealthNode)
|
|
85
|
+
for path in effective._files(effective.health_nodes)
|
|
86
|
+
],
|
|
87
|
+
health_statuses=[
|
|
88
|
+
_read(path, HealthStatus)
|
|
89
|
+
for path in effective._files(effective.health_statuses)
|
|
90
|
+
],
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def _files(self, directories: list[str]) -> list[Path]:
|
|
94
|
+
"""List contributions in source order, deduplicating canonical paths."""
|
|
95
|
+
files: list[Path] = []
|
|
96
|
+
seen: set[Path] = set()
|
|
97
|
+
for source in self._sources(directories):
|
|
98
|
+
if not _is_directory(source):
|
|
99
|
+
continue
|
|
100
|
+
for candidate in _walk(source.resolve(strict=True)):
|
|
101
|
+
canonical = candidate.resolve(strict=True)
|
|
102
|
+
if canonical not in seen:
|
|
103
|
+
seen.add(canonical)
|
|
104
|
+
files.append(canonical)
|
|
105
|
+
return files
|
|
106
|
+
|
|
107
|
+
def _sources(self, directories: list[str]) -> list[Path]:
|
|
108
|
+
"""Expand whole-segment wildcards over real directories in lexical order."""
|
|
109
|
+
sources = []
|
|
110
|
+
for directory in directories:
|
|
111
|
+
path = Path(directory)
|
|
112
|
+
if (
|
|
113
|
+
not path.is_absolute()
|
|
114
|
+
or ".." in path.parts
|
|
115
|
+
or any("*" in part and part != "*" for part in path.parts)
|
|
116
|
+
):
|
|
117
|
+
raise ValueError(
|
|
118
|
+
"Directory must be absolute without '..' "
|
|
119
|
+
f"and use only whole '*' segments: {directory!r}"
|
|
120
|
+
)
|
|
121
|
+
matches = [self.root]
|
|
122
|
+
for part in path.parts[1:]:
|
|
123
|
+
if part == "*":
|
|
124
|
+
matches = [
|
|
125
|
+
entry
|
|
126
|
+
for source in matches
|
|
127
|
+
if _is_directory(source)
|
|
128
|
+
for entry in sorted(source.iterdir())
|
|
129
|
+
if not entry.is_symlink() and entry.is_dir()
|
|
130
|
+
]
|
|
131
|
+
else:
|
|
132
|
+
matches = [source / part for source in matches]
|
|
133
|
+
sources.extend(matches)
|
|
134
|
+
return sources
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _is_directory(path: Path) -> bool:
|
|
138
|
+
"""Accept directories and missing optional sources, reporting other failures."""
|
|
139
|
+
try:
|
|
140
|
+
metadata = path.stat()
|
|
141
|
+
except FileNotFoundError:
|
|
142
|
+
if path.is_symlink():
|
|
143
|
+
raise OSError(f"Broken directory symlink: {path}") from None
|
|
144
|
+
return False
|
|
145
|
+
if not stat.S_ISDIR(metadata.st_mode):
|
|
146
|
+
raise NotADirectoryError(path)
|
|
147
|
+
return True
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _walk(directory: Path) -> list[Path]:
|
|
151
|
+
"""Recurse in lexical order without following contributed symlinks."""
|
|
152
|
+
result = []
|
|
153
|
+
for path in sorted(directory.iterdir()):
|
|
154
|
+
if path.is_symlink():
|
|
155
|
+
continue
|
|
156
|
+
if path.is_dir():
|
|
157
|
+
result.extend(_walk(path))
|
|
158
|
+
elif path.is_file() and path.suffix == ".json":
|
|
159
|
+
result.append(path)
|
|
160
|
+
return result
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _read(path: Path, model: type[Model]) -> Model:
|
|
164
|
+
"""Parse one typed contribution with its file path attached to errors."""
|
|
165
|
+
try:
|
|
166
|
+
return model.model_validate(json.loads(path.read_bytes()))
|
|
167
|
+
except (OSError, ValueError) as error:
|
|
168
|
+
raise ValueError(f"Failed to read {path}: {error}") from error
|
system_runtime/health.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Evaluate health graphs using caller-supplied boot-time evidence."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections import deque
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from .models.health import (
|
|
10
|
+
HealthContext,
|
|
11
|
+
HealthNode,
|
|
12
|
+
HealthNodeId,
|
|
13
|
+
HealthNodeResult,
|
|
14
|
+
HealthReport,
|
|
15
|
+
HealthRule_Observed,
|
|
16
|
+
HealthRule_Threshold,
|
|
17
|
+
HealthState,
|
|
18
|
+
HealthState_Degraded,
|
|
19
|
+
HealthState_Healthy,
|
|
20
|
+
HealthState_Unhealthy,
|
|
21
|
+
HealthState_Unknown,
|
|
22
|
+
HealthStatus,
|
|
23
|
+
)
|
|
24
|
+
from .models.value import ValueDefinition, ValueObservation
|
|
25
|
+
from .threshold import ValueEvidence
|
|
26
|
+
|
|
27
|
+
StateName = Literal["healthy", "degraded", "unhealthy", "unknown"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def current_context() -> HealthContext:
|
|
31
|
+
"""Read the Linux boot identifier and CLOCK_BOOTTIME in milliseconds."""
|
|
32
|
+
return HealthContext(
|
|
33
|
+
boot_id=Path("/proc/sys/kernel/random/boot_id").read_text().strip(),
|
|
34
|
+
now_ms=time.clock_gettime_ns(time.CLOCK_BOOTTIME) // 1_000_000,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def evaluate_health(
|
|
39
|
+
nodes: Sequence[HealthNode],
|
|
40
|
+
statuses: Sequence[HealthStatus],
|
|
41
|
+
context: HealthContext,
|
|
42
|
+
*,
|
|
43
|
+
values: Sequence[ValueDefinition] = (),
|
|
44
|
+
value_observations: Sequence[ValueObservation] = (),
|
|
45
|
+
) -> HealthReport:
|
|
46
|
+
"""Validate the graph, then evaluate every node in declaration order.
|
|
47
|
+
|
|
48
|
+
Malformed graphs and duplicate observations raise ValueError. Missing, expired,
|
|
49
|
+
future, wrong-boot, or wrong-tag evidence yields unknown health.
|
|
50
|
+
"""
|
|
51
|
+
evidence = ValueEvidence(values, value_observations)
|
|
52
|
+
by_id = {node.id: node for node in nodes}
|
|
53
|
+
if len(by_id) != len(nodes):
|
|
54
|
+
raise ValueError("Duplicate health node ID")
|
|
55
|
+
observations = {status.id: status for status in statuses}
|
|
56
|
+
if len(observations) != len(statuses):
|
|
57
|
+
raise ValueError("Duplicate health status ID")
|
|
58
|
+
for status in statuses:
|
|
59
|
+
if status.max_age_ms == 0:
|
|
60
|
+
raise ValueError(f"Status {status.id!r} has zero maxAgeMs")
|
|
61
|
+
if status.id in by_id and not isinstance(
|
|
62
|
+
by_id[status.id].rule, HealthRule_Observed
|
|
63
|
+
):
|
|
64
|
+
raise ValueError(f"Status supplied for derived node {status.id!r}")
|
|
65
|
+
remaining: dict[HealthNodeId, int] = {}
|
|
66
|
+
dependents: dict[HealthNodeId, list[HealthNodeId]] = {node.id: [] for node in nodes}
|
|
67
|
+
for node in nodes:
|
|
68
|
+
rule = node.rule
|
|
69
|
+
if isinstance(rule, HealthRule_Observed):
|
|
70
|
+
if rule.max_age_ms == 0:
|
|
71
|
+
raise ValueError(f"Node {node.id!r} has zero maxAgeMs")
|
|
72
|
+
remaining[node.id] = 0
|
|
73
|
+
elif isinstance(rule, HealthRule_Threshold):
|
|
74
|
+
evidence.validate(rule)
|
|
75
|
+
remaining[node.id] = 0
|
|
76
|
+
else:
|
|
77
|
+
if not 1 <= rule.required <= rule.healthy <= len(rule.inputs):
|
|
78
|
+
raise ValueError(f"Invalid thresholds for {node.id!r}")
|
|
79
|
+
if len(set(rule.inputs)) != len(rule.inputs):
|
|
80
|
+
raise ValueError(f"Duplicate input for {node.id!r}")
|
|
81
|
+
remaining[node.id] = len(rule.inputs)
|
|
82
|
+
for input_id in rule.inputs:
|
|
83
|
+
if input_id not in by_id:
|
|
84
|
+
raise ValueError(f"Missing health node {input_id!r}")
|
|
85
|
+
dependents[input_id].append(node.id)
|
|
86
|
+
ready = deque(id for id, count in remaining.items() if count == 0)
|
|
87
|
+
results: dict[HealthNodeId, HealthNodeResult] = {}
|
|
88
|
+
can_be_healthy: dict[HealthNodeId, bool] = {}
|
|
89
|
+
while ready:
|
|
90
|
+
id = ready.popleft()
|
|
91
|
+
node = by_id[id]
|
|
92
|
+
if isinstance(node.rule, HealthRule_Observed):
|
|
93
|
+
results[id] = _observe(node, observations.get(id), context)
|
|
94
|
+
can_be_healthy[id] = results[id].state.root in ("healthy", "unknown")
|
|
95
|
+
elif isinstance(node.rule, HealthRule_Threshold):
|
|
96
|
+
results[id] = evidence.evaluate(node, context)
|
|
97
|
+
can_be_healthy[id] = results[id].state.root in ("healthy", "unknown")
|
|
98
|
+
else:
|
|
99
|
+
inputs = [results[id] for id in node.rule.inputs]
|
|
100
|
+
healthy = sum(result.state.root == "healthy" for result in inputs)
|
|
101
|
+
possible_healthy = sum(
|
|
102
|
+
can_be_healthy[input_id] for input_id in node.rule.inputs
|
|
103
|
+
)
|
|
104
|
+
can_be_healthy[id] = possible_healthy >= node.rule.healthy
|
|
105
|
+
usable = sum(result.usable is True for result in inputs)
|
|
106
|
+
possible_usable = sum(result.usable is not False for result in inputs)
|
|
107
|
+
state: StateName
|
|
108
|
+
if healthy >= node.rule.healthy:
|
|
109
|
+
state = "healthy"
|
|
110
|
+
elif possible_usable < node.rule.required:
|
|
111
|
+
state = "unhealthy"
|
|
112
|
+
elif usable < node.rule.required or possible_healthy >= node.rule.healthy:
|
|
113
|
+
state = "unknown"
|
|
114
|
+
else:
|
|
115
|
+
state = "degraded"
|
|
116
|
+
results[id] = HealthNodeResult(
|
|
117
|
+
id=id,
|
|
118
|
+
origin=node.origin,
|
|
119
|
+
state=_state(state),
|
|
120
|
+
inputs=node.rule.inputs,
|
|
121
|
+
usable=True
|
|
122
|
+
if usable >= node.rule.required
|
|
123
|
+
else (False if possible_usable < node.rule.required else None),
|
|
124
|
+
)
|
|
125
|
+
for dependent in dependents[id]:
|
|
126
|
+
remaining[dependent] -= 1
|
|
127
|
+
if remaining[dependent] == 0:
|
|
128
|
+
ready.append(dependent)
|
|
129
|
+
if len(results) != len(nodes):
|
|
130
|
+
raise ValueError("Cycle in health graph")
|
|
131
|
+
return HealthReport(nodes=[results[node.id] for node in nodes])
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _observe(
|
|
135
|
+
node: HealthNode, status: HealthStatus | None, context: HealthContext
|
|
136
|
+
) -> HealthNodeResult:
|
|
137
|
+
"""Apply freshness and identity constraints to one observed node."""
|
|
138
|
+
rule = node.rule
|
|
139
|
+
assert isinstance(rule, HealthRule_Observed)
|
|
140
|
+
reason: str | None = None
|
|
141
|
+
if status is None:
|
|
142
|
+
reason = "Missing status"
|
|
143
|
+
elif status.boot_id != context.boot_id:
|
|
144
|
+
reason = "Status belongs to another boot"
|
|
145
|
+
elif node.origin is not None and status.origin != node.origin:
|
|
146
|
+
reason = "Status origin does not match"
|
|
147
|
+
elif rule.expected_tag is not None and status.tag != rule.expected_tag:
|
|
148
|
+
reason = "Status tag does not match"
|
|
149
|
+
elif status.observed_at_ms > context.now_ms:
|
|
150
|
+
reason = "Status is in the future"
|
|
151
|
+
elif context.now_ms - status.observed_at_ms >= min(
|
|
152
|
+
status.max_age_ms,
|
|
153
|
+
rule.max_age_ms if rule.max_age_ms is not None else status.max_age_ms,
|
|
154
|
+
):
|
|
155
|
+
reason = "Status has expired"
|
|
156
|
+
if reason is not None:
|
|
157
|
+
return HealthNodeResult(
|
|
158
|
+
id=node.id,
|
|
159
|
+
origin=node.origin,
|
|
160
|
+
state=_state("unknown"),
|
|
161
|
+
inputs=[],
|
|
162
|
+
message=reason,
|
|
163
|
+
)
|
|
164
|
+
assert status is not None
|
|
165
|
+
name = status.state.root
|
|
166
|
+
return HealthNodeResult(
|
|
167
|
+
id=node.id,
|
|
168
|
+
origin=node.origin,
|
|
169
|
+
state=status.state,
|
|
170
|
+
inputs=[],
|
|
171
|
+
message=status.message,
|
|
172
|
+
usable=None if name == "unknown" else name in ("healthy", "degraded"),
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _state(name: StateName) -> HealthState:
|
|
177
|
+
"""Construct the generated externally tagged state model."""
|
|
178
|
+
match name:
|
|
179
|
+
case "healthy":
|
|
180
|
+
return HealthState_Healthy(name)
|
|
181
|
+
case "degraded":
|
|
182
|
+
return HealthState_Degraded(name)
|
|
183
|
+
case "unhealthy":
|
|
184
|
+
return HealthState_Unhealthy(name)
|
|
185
|
+
case "unknown":
|
|
186
|
+
return HealthState_Unknown(name)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# DO NOT EDIT! This file is autogenerated.
|
|
2
|
+
|
|
3
|
+
import pydantic
|
|
4
|
+
|
|
5
|
+
from . import component # noqa: F401
|
|
6
|
+
from . import filesystem # noqa: F401
|
|
7
|
+
from . import health # noqa: F401
|
|
8
|
+
from . import value # noqa: F401
|
|
9
|
+
|
|
10
|
+
_schemas = {"component": component, "filesystem": filesystem, "health": health, "value": value}
|
|
11
|
+
for _m in _schemas.values():
|
|
12
|
+
for _name, _other in _schemas.items():
|
|
13
|
+
_alias = f"_schema_{_name}"
|
|
14
|
+
if not hasattr(_m, _alias):
|
|
15
|
+
setattr(_m, _alias, _other)
|
|
16
|
+
for _m in _schemas.values():
|
|
17
|
+
for _attr in dir(_m):
|
|
18
|
+
_obj = getattr(_m, _attr)
|
|
19
|
+
if isinstance(_obj, type) and issubclass(_obj, pydantic.BaseModel) and not _obj.__pydantic_complete__:
|
|
20
|
+
_obj.model_rebuild()
|