From fc9bb0dd9d183d7ceedd7e8a922e2269160d55ce Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 20 Jun 2026 15:25:26 +0200 Subject: [PATCH] refactor(ressources): move resource collection/aggregation to utils (single spot) Move the parse/collect/aggregate logic out of the ressources CLI into utils/roles/applications/services/resources.py so the CLI and the upcoming variant resource-budget guard share one implementation instead of duplicating it. The CLI's query/__main__ and the unit tests now import from utils; the per-module CLI files (parse.py, collect.py, aggregate.py) are removed. No behavior change: the 43 ressources unit tests pass. Co-Authored-By: Claude Opus 4.8 --- .../roles/applications/ressources/__main__.py | 7 +- .../applications/ressources/aggregate.py | 67 ----- .../roles/applications/ressources/collect.py | 131 --------- .../roles/applications/ressources/parse.py | 89 ------ .../roles/applications/ressources/query.py | 6 +- .../applications/ressources/test_aggregate.py | 2 +- .../applications/ressources/test_collect.py | 2 +- .../applications/ressources/test_parse.py | 2 +- .../applications/ressources/test_render.py | 9 +- .../roles/applications/services/resources.py | 264 ++++++++++++++++++ 10 files changed, 282 insertions(+), 297 deletions(-) delete mode 100644 cli/meta/roles/applications/ressources/aggregate.py delete mode 100644 cli/meta/roles/applications/ressources/collect.py delete mode 100644 cli/meta/roles/applications/ressources/parse.py create mode 100644 utils/roles/applications/services/resources.py diff --git a/cli/meta/roles/applications/ressources/__main__.py b/cli/meta/roles/applications/ressources/__main__.py index fef3d0d014..bf9edff4b7 100755 --- a/cli/meta/roles/applications/ressources/__main__.py +++ b/cli/meta/roles/applications/ressources/__main__.py @@ -18,9 +18,12 @@ from utils.roles.applications.services.registry import ( build_service_registry_from_applications, load_applications_from_roles_dir, ) +from utils.roles.applications.services.resources import ( + SUMMABLE_FIELDS, + aggregate, + collect_role_resources, +) -from .aggregate import SUMMABLE_FIELDS, aggregate -from .collect import collect_role_resources from .query import apply_filters, apply_order from .render import DEFAULT_TOTAL_LABEL, render_json, render_text diff --git a/cli/meta/roles/applications/ressources/aggregate.py b/cli/meta/roles/applications/ressources/aggregate.py deleted file mode 100644 index 69cf8ec961..0000000000 --- a/cli/meta/roles/applications/ressources/aggregate.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Aggregate per-service resource rows into a single budget. - -Default (``sum_fields is None``): mem_reservation / mem_limit are summed, -pids_limit is summed (max-provisioned host-pid budget), cpus is the max (shared -across containers, not additive); bond is not aggregated. - -``--sum`` mode (``sum_fields`` is a list): every requested field is summed -(an empty list means all summable fields); unrequested fields stay ``None``.""" - -from __future__ import annotations - -from typing import Any - -SUMMABLE_FIELDS: dict[str, str] = { - "mem_reservation": "mem_reservation_bytes", - "mem_limit": "mem_limit_bytes", - "pids_limit": "pids_limit_int", - "cpus": "cpus_float", - "bond": "bond_float", -} - - -def _sum_column(rows: list[dict[str, Any]], column: str) -> Any: - values = [row.get(column) for row in rows if row.get(column) is not None] - return sum(values) if values else None - - -def aggregate( - rows: list[dict[str, Any]], sum_fields: list[str] | None = None -) -> dict[str, Any]: - if sum_fields is not None: - fields = sum_fields or list(SUMMABLE_FIELDS) - totals: dict[str, Any] = dict.fromkeys(SUMMABLE_FIELDS.values()) - for field in fields: - column = SUMMABLE_FIELDS.get(field) - if column is None: - raise ValueError(f"unknown sum field: '{field}'") - totals[column] = _sum_column(rows, column) - return totals - - total_mem_res = 0 - total_mem_lim = 0 - total_pids = 0 - max_cpus = 0.0 - any_mem_res = any_mem_lim = any_pids = any_cpus = False - - for row in rows: - if row["mem_reservation_bytes"] is not None: - total_mem_res += row["mem_reservation_bytes"] - any_mem_res = True - if row["mem_limit_bytes"] is not None: - total_mem_lim += row["mem_limit_bytes"] - any_mem_lim = True - if row["pids_limit_int"] is not None: - total_pids += row["pids_limit_int"] - any_pids = True - if row["cpus_float"] is not None: - max_cpus = max(max_cpus, row["cpus_float"]) - any_cpus = True - - return { - "mem_reservation_bytes": total_mem_res if any_mem_res else None, - "mem_limit_bytes": total_mem_lim if any_mem_lim else None, - "pids_limit_int": total_pids if any_pids else None, - "cpus_float": max_cpus if any_cpus else None, - "bond_float": None, - } diff --git a/cli/meta/roles/applications/ressources/collect.py b/cli/meta/roles/applications/ressources/collect.py deleted file mode 100644 index 78b9a85a6b..0000000000 --- a/cli/meta/roles/applications/ressources/collect.py +++ /dev/null @@ -1,131 +0,0 @@ -"""Walk a role's services and the shared dependencies it pulls in, emitting one -flat row per service (resolving template-gated shared services to the provider -role's entity via the service registry).""" - -from __future__ import annotations - -from typing import Any - -from utils.roles.entity_name import get_entity_name - -from .parse import ( - _as_mapping, - _has_resource_keys, - _is_enabled, - _is_shared, - _looks_like_container, - _parse_bond, - _parse_cpus, - _parse_int, - _parse_mem_bytes, -) - -_DEFAULT_BOND = 1.0 - - -def _row_for_service( - role_name: str, - service_key: str, - service_conf: dict[str, Any], - depth: int = 1, -) -> dict[str, Any]: - bond = _parse_bond(service_conf.get("bond")) - return { - "depth": depth, - "role": role_name, - "service": service_key, - "mem_reservation_raw": service_conf.get("mem_reservation"), - "mem_limit_raw": service_conf.get("mem_limit"), - "pids_limit_raw": service_conf.get("pids_limit"), - "cpus_raw": service_conf.get("cpus"), - "bond_raw": service_conf.get("bond"), - "mem_reservation_bytes": _parse_mem_bytes(service_conf.get("mem_reservation")), - "mem_limit_bytes": _parse_mem_bytes(service_conf.get("mem_limit")), - "pids_limit_int": _parse_int(service_conf.get("pids_limit")), - "cpus_float": _parse_cpus(service_conf.get("cpus")), - "bond_float": _DEFAULT_BOND if bond is None else bond, - } - - -def collect_role_resources( - role_name: str, - applications: dict[str, dict[str, Any]], - service_registry: dict[str, dict[str, Any]], - visited: set, - rows: list[dict[str, Any]], - warnings: list[str], - depth: int = 1, - max_depth: int = 0, - dedup: bool = True, - loaded: set | None = None, -) -> None: - if loaded is None: - loaded = set() - if role_name in visited: - return - visited.add(role_name) - - if role_name not in applications: - warnings.append(f"role '{role_name}' has no meta/services.yml; skipping") - return - - config = _as_mapping(applications[role_name]) - services = _as_mapping(config.get("services")) - entity_name = get_entity_name(role_name) - - def add(service_key: str, service_conf: dict[str, Any]) -> None: - if dedup and service_key in loaded: - return - loaded.add(service_key) - rows.append(_row_for_service(role_name, service_key, service_conf, depth)) - - if entity_name and entity_name in services: - add(entity_name, _as_mapping(services.get(entity_name))) - else: - warnings.append( - f"role '{role_name}' has no services.{entity_name or ''} entry" - ) - - shared_dependencies: list[str] = [] - for service_key, raw_service_conf in services.items(): - if service_key == entity_name: - continue - service_conf = _as_mapping(raw_service_conf) - if not service_conf: - continue - - if not _is_enabled( - service_conf, default_enabled=_looks_like_container(service_conf) - ): - continue - - provider = _as_mapping(service_registry.get(service_key)) - provider_role = provider.get("role") if provider else None - - if _has_resource_keys(service_conf): - add(service_key, service_conf) - elif provider_role and provider_role != role_name: - shared_dependencies.append(provider_role) - elif _is_shared(service_conf): - warnings.append( - f"{role_name}: shared service '{service_key}' has no registered provider" - ) - elif _looks_like_container(service_conf): - add(service_key, service_conf) - - if max_depth != 0 and depth >= max_depth: - return - - for provider_role in shared_dependencies: - collect_role_resources( - provider_role, - applications, - service_registry, - visited, - rows, - warnings, - depth=depth + 1, - max_depth=max_depth, - dedup=dedup, - loaded=loaded, - ) diff --git a/cli/meta/roles/applications/ressources/parse.py b/cli/meta/roles/applications/ressources/parse.py deleted file mode 100644 index 0af659d49a..0000000000 --- a/cli/meta/roles/applications/ressources/parse.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Interpret raw service-config values: parse resource scalars and evaluate the -enabled/shared/container predicates a service entry exposes.""" - -from __future__ import annotations - -from typing import Any - -from humanfriendly import parse_size - -_RESOURCE_KEYS = ("mem_reservation", "mem_limit", "pids_limit", "cpus") -_CONTAINER_KEYS = ("image", "name", "version", "container") - - -def _as_mapping(value: Any) -> dict[str, Any]: - return value if isinstance(value, dict) else {} - - -def _parse_mem_bytes(value: Any) -> int | None: - if value is None: - return None - if isinstance(value, (int, float)): - return int(value) - text = str(value).strip() - if not text: - return None - try: - return int(parse_size(text)) - except Exception: - return None - - -def _parse_cpus(value: Any) -> float | None: - if value is None: - return None - if isinstance(value, (int, float)): - return float(value) - try: - return float(str(value).strip()) - except (TypeError, ValueError): - return None - - -def _parse_int(value: Any) -> int | None: - if value is None: - return None - if isinstance(value, bool): - return None - if isinstance(value, int): - return value - try: - return int(str(value).strip()) - except (TypeError, ValueError): - return None - - -def _parse_bond(value: Any) -> float | None: - if isinstance(value, bool): - return None - if isinstance(value, (int, float)): - return float(value) - try: - return float(str(value).strip()) - except (TypeError, ValueError): - return None - - -def _is_enabled(service_conf: dict[str, Any], default_enabled: bool) -> bool: - if "enabled" not in service_conf: - return default_enabled - raw = service_conf.get("enabled") - if isinstance(raw, bool): - return raw - text = str(raw).strip().lower() - return text not in ("false", "0", "no", "off") - - -def _is_shared(service_conf: dict[str, Any]) -> bool: - raw = service_conf.get("shared", False) - if isinstance(raw, bool): - return raw - return str(raw).strip().lower() in ("true", "1", "yes", "on") - - -def _looks_like_container(service_conf: dict[str, Any]) -> bool: - return any(key in service_conf for key in _RESOURCE_KEYS + _CONTAINER_KEYS) - - -def _has_resource_keys(service_conf: dict[str, Any]) -> bool: - return any(key in service_conf for key in _RESOURCE_KEYS) diff --git a/cli/meta/roles/applications/ressources/query.py b/cli/meta/roles/applications/ressources/query.py index d483978169..bb7d958525 100644 --- a/cli/meta/roles/applications/ressources/query.py +++ b/cli/meta/roles/applications/ressources/query.py @@ -7,7 +7,11 @@ import operator import re from typing import TYPE_CHECKING, Any -from .parse import _parse_cpus, _parse_int, _parse_mem_bytes +from utils.roles.applications.services.resources import ( + _parse_cpus, + _parse_int, + _parse_mem_bytes, +) if TYPE_CHECKING: from collections.abc import Callable diff --git a/tests/unit/cli/meta/roles/applications/ressources/test_aggregate.py b/tests/unit/cli/meta/roles/applications/ressources/test_aggregate.py index 45e7e1ddda..de98de72e0 100644 --- a/tests/unit/cli/meta/roles/applications/ressources/test_aggregate.py +++ b/tests/unit/cli/meta/roles/applications/ressources/test_aggregate.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from cli.meta.roles.applications.ressources import aggregate as cli +from utils.roles.applications.services import resources as cli class TestAggregate(unittest.TestCase): diff --git a/tests/unit/cli/meta/roles/applications/ressources/test_collect.py b/tests/unit/cli/meta/roles/applications/ressources/test_collect.py index 86afafb26a..f9548a59d8 100644 --- a/tests/unit/cli/meta/roles/applications/ressources/test_collect.py +++ b/tests/unit/cli/meta/roles/applications/ressources/test_collect.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from cli.meta.roles.applications.ressources import collect as cli +from utils.roles.applications.services import resources as cli class TestCollectRoleResources(unittest.TestCase): diff --git a/tests/unit/cli/meta/roles/applications/ressources/test_parse.py b/tests/unit/cli/meta/roles/applications/ressources/test_parse.py index 2822cf72b8..107bd7d970 100644 --- a/tests/unit/cli/meta/roles/applications/ressources/test_parse.py +++ b/tests/unit/cli/meta/roles/applications/ressources/test_parse.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from cli.meta.roles.applications.ressources import parse as cli +from utils.roles.applications.services import resources as cli class TestParsingHelpers(unittest.TestCase): diff --git a/tests/unit/cli/meta/roles/applications/ressources/test_render.py b/tests/unit/cli/meta/roles/applications/ressources/test_render.py index d769b2a564..ffca1833bd 100644 --- a/tests/unit/cli/meta/roles/applications/ressources/test_render.py +++ b/tests/unit/cli/meta/roles/applications/ressources/test_render.py @@ -3,7 +3,8 @@ from __future__ import annotations import json import unittest -from cli.meta.roles.applications.ressources import aggregate, render +from cli.meta.roles.applications.ressources import render +from utils.roles.applications.services import resources class TestRenderText(unittest.TestCase): @@ -46,7 +47,7 @@ class TestRenderText(unittest.TestCase): "cpus_float": 4.0, }, ] - totals = aggregate.aggregate(rows) + totals = resources.aggregate(rows) text = render.render_text("web-app-peertube", rows, totals, warnings=[]) lines = text.splitlines() @@ -68,7 +69,7 @@ class TestRenderText(unittest.TestCase): text = render.render_text( role_name="web-app-x", rows=[], - totals=aggregate.aggregate([]), + totals=resources.aggregate([]), warnings=["shared service 'foo' has no registered provider"], ) self.assertIn("# Warnings", text) @@ -91,7 +92,7 @@ class TestRenderJson(unittest.TestCase): "cpus_float": 4.0, } ] - totals = aggregate.aggregate(rows) + totals = resources.aggregate(rows) payload = json.loads( render.render_json("web-app-peertube", rows, totals, warnings=["w"]) ) diff --git a/utils/roles/applications/services/resources.py b/utils/roles/applications/services/resources.py new file mode 100644 index 0000000000..a738c55de3 --- /dev/null +++ b/utils/roles/applications/services/resources.py @@ -0,0 +1,264 @@ +"""Compute the compose-resource footprint of a role and its shared dependencies. + +Single source of truth for: parsing raw service-config resource scalars, +evaluating the enabled/shared/container predicates, walking a role's services +(resolving template-gated shared services to the provider role's entity via the +service registry, loading each service once unless ``dedup=False``), and +aggregating the collected rows into a budget. + +Used by the ``ressources`` CLI and by the variant resource-budget lint, so the +collection/aggregation logic lives here once (no duplication).""" + +from __future__ import annotations + +from typing import Any + +from humanfriendly import parse_size + +from utils.roles.entity_name import get_entity_name + +_RESOURCE_KEYS = ("mem_reservation", "mem_limit", "pids_limit", "cpus") +_CONTAINER_KEYS = ("image", "name", "version", "container") +_DEFAULT_BOND = 1.0 + + +def _as_mapping(value: Any) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + +def _parse_mem_bytes(value: Any) -> int | None: + if value is None: + return None + if isinstance(value, (int, float)): + return int(value) + text = str(value).strip() + if not text: + return None + try: + return int(parse_size(text)) + except Exception: + return None + + +def _parse_cpus(value: Any) -> float | None: + if value is None: + return None + if isinstance(value, (int, float)): + return float(value) + try: + return float(str(value).strip()) + except (TypeError, ValueError): + return None + + +def _parse_int(value: Any) -> int | None: + if value is None: + return None + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + try: + return int(str(value).strip()) + except (TypeError, ValueError): + return None + + +def _parse_bond(value: Any) -> float | None: + if isinstance(value, bool): + return None + if isinstance(value, (int, float)): + return float(value) + try: + return float(str(value).strip()) + except (TypeError, ValueError): + return None + + +def _is_enabled(service_conf: dict[str, Any], default_enabled: bool) -> bool: + if "enabled" not in service_conf: + return default_enabled + raw = service_conf.get("enabled") + if isinstance(raw, bool): + return raw + text = str(raw).strip().lower() + return text not in ("false", "0", "no", "off") + + +def _is_shared(service_conf: dict[str, Any]) -> bool: + raw = service_conf.get("shared", False) + if isinstance(raw, bool): + return raw + return str(raw).strip().lower() in ("true", "1", "yes", "on") + + +def _looks_like_container(service_conf: dict[str, Any]) -> bool: + return any(key in service_conf for key in _RESOURCE_KEYS + _CONTAINER_KEYS) + + +def _has_resource_keys(service_conf: dict[str, Any]) -> bool: + return any(key in service_conf for key in _RESOURCE_KEYS) + + +def _row_for_service( + role_name: str, + service_key: str, + service_conf: dict[str, Any], + depth: int = 1, +) -> dict[str, Any]: + bond = _parse_bond(service_conf.get("bond")) + return { + "depth": depth, + "role": role_name, + "service": service_key, + "mem_reservation_raw": service_conf.get("mem_reservation"), + "mem_limit_raw": service_conf.get("mem_limit"), + "pids_limit_raw": service_conf.get("pids_limit"), + "cpus_raw": service_conf.get("cpus"), + "bond_raw": service_conf.get("bond"), + "mem_reservation_bytes": _parse_mem_bytes(service_conf.get("mem_reservation")), + "mem_limit_bytes": _parse_mem_bytes(service_conf.get("mem_limit")), + "pids_limit_int": _parse_int(service_conf.get("pids_limit")), + "cpus_float": _parse_cpus(service_conf.get("cpus")), + "bond_float": _DEFAULT_BOND if bond is None else bond, + } + + +def collect_role_resources( + role_name: str, + applications: dict[str, dict[str, Any]], + service_registry: dict[str, dict[str, Any]], + visited: set, + rows: list[dict[str, Any]], + warnings: list[str], + depth: int = 1, + max_depth: int = 0, + dedup: bool = True, + loaded: set | None = None, +) -> None: + if loaded is None: + loaded = set() + if role_name in visited: + return + visited.add(role_name) + + if role_name not in applications: + warnings.append(f"role '{role_name}' has no meta/services.yml; skipping") + return + + config = _as_mapping(applications[role_name]) + services = _as_mapping(config.get("services")) + entity_name = get_entity_name(role_name) + + def add(service_key: str, service_conf: dict[str, Any]) -> None: + if dedup and service_key in loaded: + return + loaded.add(service_key) + rows.append(_row_for_service(role_name, service_key, service_conf, depth)) + + if entity_name and entity_name in services: + add(entity_name, _as_mapping(services.get(entity_name))) + else: + warnings.append( + f"role '{role_name}' has no services.{entity_name or ''} entry" + ) + + shared_dependencies: list[str] = [] + for service_key, raw_service_conf in services.items(): + if service_key == entity_name: + continue + service_conf = _as_mapping(raw_service_conf) + if not service_conf: + continue + + if not _is_enabled( + service_conf, default_enabled=_looks_like_container(service_conf) + ): + continue + + provider = _as_mapping(service_registry.get(service_key)) + provider_role = provider.get("role") if provider else None + + if _has_resource_keys(service_conf): + add(service_key, service_conf) + elif provider_role and provider_role != role_name: + shared_dependencies.append(provider_role) + elif _is_shared(service_conf): + warnings.append( + f"{role_name}: shared service '{service_key}' has no registered provider" + ) + elif _looks_like_container(service_conf): + add(service_key, service_conf) + + if max_depth != 0 and depth >= max_depth: + return + + for provider_role in shared_dependencies: + collect_role_resources( + provider_role, + applications, + service_registry, + visited, + rows, + warnings, + depth=depth + 1, + max_depth=max_depth, + dedup=dedup, + loaded=loaded, + ) + + +SUMMABLE_FIELDS: dict[str, str] = { + "mem_reservation": "mem_reservation_bytes", + "mem_limit": "mem_limit_bytes", + "pids_limit": "pids_limit_int", + "cpus": "cpus_float", + "bond": "bond_float", +} + + +def _sum_column(rows: list[dict[str, Any]], column: str) -> Any: + values = [row.get(column) for row in rows if row.get(column) is not None] + return sum(values) if values else None + + +def aggregate( + rows: list[dict[str, Any]], sum_fields: list[str] | None = None +) -> dict[str, Any]: + if sum_fields is not None: + fields = sum_fields or list(SUMMABLE_FIELDS) + totals: dict[str, Any] = dict.fromkeys(SUMMABLE_FIELDS.values()) + for field in fields: + column = SUMMABLE_FIELDS.get(field) + if column is None: + raise ValueError(f"unknown sum field: '{field}'") + totals[column] = _sum_column(rows, column) + return totals + + total_mem_res = 0 + total_mem_lim = 0 + total_pids = 0 + max_cpus = 0.0 + any_mem_res = any_mem_lim = any_pids = any_cpus = False + + for row in rows: + if row["mem_reservation_bytes"] is not None: + total_mem_res += row["mem_reservation_bytes"] + any_mem_res = True + if row["mem_limit_bytes"] is not None: + total_mem_lim += row["mem_limit_bytes"] + any_mem_lim = True + if row["pids_limit_int"] is not None: + total_pids += row["pids_limit_int"] + any_pids = True + if row["cpus_float"] is not None: + max_cpus = max(max_cpus, row["cpus_float"]) + any_cpus = True + + return { + "mem_reservation_bytes": total_mem_res if any_mem_res else None, + "mem_limit_bytes": total_mem_lim if any_mem_lim else None, + "pids_limit_int": total_pids if any_pids else None, + "cpus_float": max_cpus if any_cpus else None, + "bond_float": None, + }