diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index b0af51f9eb..4dd42d205a 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -1,14 +1,7 @@ --- # Webserver Configuration -# Effective CPUs (float) across proxy and the current app -WEBSERVER_CPUS_EFFECTIVE: >- - {{ - [ - (lookup('applications') | resource_filter('svc-prx-openresty', 'cpus', service_name | default(''), RESOURCE_CPUS)) | float, - (lookup('applications') | resource_filter(application_id, 'cpus', service_name | default(''), RESOURCE_CPUS)) | float - ] | min - }} +WEBSERVER_CPUS_EFFECTIVE: "{{ lookup('webserver_resource', 'cpus') }}" WEBSERVER_WORKER_PROCESSES: >- {{ @@ -16,11 +9,4 @@ WEBSERVER_WORKER_PROCESSES: >- else (WEBSERVER_CPUS_EFFECTIVE | float | int) }} -# worker_connections from pids_limit (use the smaller one), with correct key/defaults -WEBSERVER_WORKER_CONNECTIONS: >- - {{ - [ - (lookup('applications') | resource_filter('svc-prx-openresty', 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT)) | int, - (lookup('applications') | resource_filter(application_id, 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT)) | int - ] | min - }} +WEBSERVER_WORKER_CONNECTIONS: "{{ lookup('webserver_resource', 'pids_limit') }}" diff --git a/plugins/filter/resource_filter.py b/plugins/filter/resource_filter.py index fab2899761..d449c4399d 100644 --- a/plugins/filter/resource_filter.py +++ b/plugins/filter/resource_filter.py @@ -11,6 +11,57 @@ from utils.roles.entity.name import get_entity_name _UNSET = object() +_CPU_GRANULARITY = 0.01 +_FULL_PERCENT = 100 + + +def _is_zero(value) -> bool: + if isinstance(value, bool): + return False + if isinstance(value, (int, float)): + return value == 0 + try: + return float(str(value).strip()) == 0 + except (TypeError, ValueError): + return False + + +def resolve_cpus(value, host_cpus): + """Return the share a percentage names, the value itself otherwise. + + A percentage is read against every CPU the host has, not against the + fair-share default, so ``100%`` is the whole machine and lands exactly on + the ceiling docker accepts. + + Args: + value: the configured ``cpus``, either a plain number as docker takes + it or a percentage such as ``"50%"``. + host_cpus: the host's CPU count, normally ``RESOURCE_HOST_CPUS``. + + Raises: + AnsibleFilterError: the percentage is unreadable or outside 0 to 100, + or the value is a bare zero, which docker reads as *uncapped* + rather than as none. + """ + text = str(value).strip() + if not text.endswith("%"): + if _is_zero(value): + raise AnsibleFilterError( + f"cpus: {value!r} leaves the container uncapped; " + "write '100%' to ask for every CPU the host has" + ) + return value + try: + percent = float(text[:-1]) + except ValueError as e: + raise AnsibleFilterError(f"cpus: {value!r} is not a percentage") from e + if not 0 <= percent <= _FULL_PERCENT: + raise AnsibleFilterError( + f"cpus: {value!r} is outside 0% to 100%; docker refuses more CPUs " + "than the host has" + ) + return max(round(float(host_cpus) * percent / _FULL_PERCENT, 2), _CPU_GRANULARITY) + def resource_filter( applications: dict, @@ -18,6 +69,7 @@ def resource_filter( key: str, service_name: str, hard_default, + host_cpus=None, ): """ Lookup order: @@ -28,6 +80,9 @@ def resource_filter( - service_name may be "" → will resolve to get_entity_name(application_id). - hard_default is mandatory (no implicit None). - required=False always. + - host_cpus, when given, resolves a percentage through + :func:`resolve_cpus`. Callers reading ``cpus`` pass RESOURCE_HOST_CPUS + so that ``cpus: 50%`` in services.yml means half of the host. """ try: entity = get_entity_name(application_id) @@ -45,7 +100,10 @@ def resource_filter( break except (AppConfigKeyError, ConfigEntryNotSetError) as e: raise AnsibleFilterError(str(e)) from e - return hard_default if value is _UNSET else value + resolved = hard_default if value is _UNSET else value + if host_cpus is not None: + return resolve_cpus(resolved, host_cpus) + return resolved class FilterModule: diff --git a/plugins/lookup/cpus.py b/plugins/lookup/cpus.py new file mode 100644 index 0000000000..863dd8929f --- /dev/null +++ b/plugins/lookup/cpus.py @@ -0,0 +1,50 @@ +"""The CPU cap of one service, with a percentage resolved against the host. + +``lookup('cpus', application_id[, service_name])`` reads +``services..cpus`` and resolves it through +:func:`plugins.filter.resource_filter.resolve_cpus`. A caller neither repeats +the resolution nor has to know that a percentage is read against the host's +raw core count rather than against the fair share, which is what every +consumer of a ``cpus`` value got wrong before this existed. + +``service_name`` defaults to the role's entity name. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from plugins.filter.resource_filter import resolve_cpus +from plugins.lookup.config import LookupModule as ConfigLookup +from plugins.lookup.resource import LookupModule as ResourceLookup +from utils.roles.entity.name import get_entity_name + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any], + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if not terms or len(terms) > 2: + raise AnsibleError( + "lookup('cpus', application_id[, service_name]) expects 1 or 2 terms." + ) + + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + application_id = str(terms[0]) + service_name = ( + str(terms[1]) if len(terms) == 2 else get_entity_name(application_id) + ) + + configured = ConfigLookup().run( + [application_id, f"services.{service_name}.cpus"], + variables=vars_, + **kwargs, + )[0] + host_cpus = ResourceLookup().run(["host_cpus"], variables=vars_, **kwargs)[0] + return [resolve_cpus(configured, host_cpus)] diff --git a/plugins/lookup/webserver_resource.py b/plugins/lookup/webserver_resource.py new file mode 100644 index 0000000000..5b4b0dbd8c --- /dev/null +++ b/plugins/lookup/webserver_resource.py @@ -0,0 +1,76 @@ +"""The resource ceiling a webserver worker pool may assume. + +``lookup('webserver_resource', key)`` is the smaller of the reverse proxy's +value for *key* and the current application's. A pool sized on either alone +over-commits whichever of the two containers is the tighter, and requests pass +through both. + +``cpus`` resolves a percentage against the host first, so a proxy or an app +written as ``95%`` contributes its share rather than the literal text. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from plugins.filter.resource_filter import resource_filter +from plugins.lookup.applications import LookupModule as ApplicationsLookup +from plugins.lookup.resource import LookupModule as ResourceLookup + +PROXY_ROLE = "svc-prx-openresty" + +_CAST = {"cpus": float, "pids_limit": int} + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any], + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if len(terms) != 1: + raise AnsibleError( + "lookup('webserver_resource', key) expects exactly one term." + ) + + key = str(terms[0]).strip() + cast = _CAST.get(key) + if cast is None: + raise AnsibleError( + f"lookup('webserver_resource', {key!r}): expected one of " + f"{sorted(_CAST)}" + ) + + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + application_id = str(vars_.get("application_id") or "") + service_name = str(vars_.get("service_name") or "") + + applications = ApplicationsLookup().run([], variables=vars_, **kwargs)[0] + resource = ResourceLookup() + hard_default = resource.run([key], variables=vars_, **kwargs)[0] + + scaling: dict[str, Any] = {} + if key == "cpus": + scaling["host_cpus"] = resource.run( + ["host_cpus"], variables=vars_, **kwargs + )[0] + + return [ + min( + cast( + resource_filter( + applications, + app_id, + key, + service_name, + hard_default, + **scaling, + ) + ) + for app_id in (PROXY_ROLE, application_id) + ) + ] diff --git a/roles/svc-ai-agent-broker/vars/main.yml b/roles/svc-ai-agent-broker/vars/main.yml index eab5f3f588..3ed8551399 100644 --- a/roles/svc-ai-agent-broker/vars/main.yml +++ b/roles/svc-ai-agent-broker/vars/main.yml @@ -37,7 +37,7 @@ AGENT_BROKER_PLATFORMS_DECLARED: API_SERVER_HOST: "0.0.0.0" API_SERVER_PORT: "{{ lookup('config', 'web-app-hermes', 'services.hermes.ports.internal.http') }}" TZ: "{{ HOST_TIMEZONE }}" - cpus: "{{ lookup('config', 'web-app-hermes', 'services.hermes.cpus') }}" + cpus: "{{ lookup('cpus', 'web-app-hermes', 'hermes') }}" mem_limit: "{{ lookup('config', 'web-app-hermes', 'services.hermes.mem_limit') | upper | human_to_bytes }}" mem_reservation: "{{ lookup('config', 'web-app-hermes', 'services.hermes.mem_reservation') | upper | human_to_bytes }}" pids_limit: "{{ lookup('config', 'web-app-hermes', 'services.hermes.pids_limit') }}" @@ -68,7 +68,7 @@ AGENT_BROKER_PLATFORMS_DECLARED: OPENCLAW_CONFIG_PATH: "{{ lookup('volume', 'web-app-openclaw', 'openclaw_config').target }}" OPENCLAW_WORKSPACE_DIR: "{{ [lookup('volume', 'web-app-openclaw', 'openclaw_data').target, 'workspace'] | path_join }}" TZ: "{{ HOST_TIMEZONE }}" - cpus: "{{ lookup('config', 'web-app-openclaw', 'services.openclaw.cpus') }}" + cpus: "{{ lookup('cpus', 'web-app-openclaw', 'openclaw') }}" mem_limit: "{{ lookup('config', 'web-app-openclaw', 'services.openclaw.mem_limit') | upper | human_to_bytes }}" mem_reservation: "{{ lookup('config', 'web-app-openclaw', 'services.openclaw.mem_reservation') | upper | human_to_bytes }}" pids_limit: "{{ lookup('config', 'web-app-openclaw', 'services.openclaw.pids_limit') }}" diff --git a/roles/svc-runner/vars/main.yml b/roles/svc-runner/vars/main.yml index e4508849da..c371dfd020 100644 --- a/roles/svc-runner/vars/main.yml +++ b/roles/svc-runner/vars/main.yml @@ -10,7 +10,7 @@ RUNNER_IMAGE_NAME: "{{ lookup('config', application_id, 'services.runner.image_n RUNNER_IMAGE_TAG: "{{ lookup('config', application_id, 'services.runner.image_tag') }}" RUNNER_IMAGE_REF: "{{ SWARM_REGISTRY_PREFIX }}{{ RUNNER_IMAGE_NAME }}:{{ RUNNER_IMAGE_TAG }}" RUNNER_INSTALL_DIR: "{{ lookup('config', application_id, 'services.runner.install_dir') }}" -RUNNER_CPUS: "{{ lookup('config', application_id, 'services.runner.cpus') | int }}" +RUNNER_CPUS: "{{ lookup('cpus', application_id, 'runner') | int }}" RUNNER_BASE_IMAGE: "{{ lookup('config', application_id, 'services.runner.image') }}:{{ lookup('config', application_id, 'services.runner.version') }}" RUNNER_DOCKER_GID_FALLBACK: "{{ lookup('config', application_id, 'services.runner.docker_gid_fallback') }}" RUNNER_GITHUB_OWNER: "{{ lookup('env', 'GITHUB_REPOSITORY_OWNER') | default(lookup('config', application_id, 'services.runner.github_owner'), true) }}" diff --git a/roles/sys-svc-container/README.md b/roles/sys-svc-container/README.md index ef51a079ad..7df24acf8b 100644 --- a/roles/sys-svc-container/README.md +++ b/roles/sys-svc-container/README.md @@ -26,6 +26,31 @@ When enabled via `MODE_CLEANUP` or `MODE_RESET`, it will automatically prune unu - **Handler Integration** Restart handler ensures the Docker daemon is reloaded when necessary. +## Resource limits + +[resource.yml.j2](templates/resource.yml.j2) renders the compose `cpus`, `mem_reservation`, `mem_limit` and `pids_limit` of every service, and [deploy.yml.j2](templates/deploy.yml.j2) renders the swarm equivalents. Each value comes from `services..` of the role's `meta/services.yml`, overridable per host in the inventory, and falls back to the fair share `lookup('resource', …)` computes from the host. + +`cpus` also takes a percentage, which is read against `RESOURCE_HOST_CPUS`: the host's raw core count, without the two-CPU host reserve and without the division by running containers that the fair-share default applies. `100%` is the whole machine, `50%` is half of it: + +```yaml +applications: + web-app-docs: + services: + docs: + cpus: 50% +``` + +A percentage is the only portable way to size against the machine. Docker refuses a `cpus` above the host's core count (`range of CPUs is from 0.01 to N.00`), so `cpus: "4"` is a hard failure on a two-core host while `50%` is valid everywhere. `100%` resolves to exactly that ceiling and can never be rejected. + +Shares are rounded to `0.01`, Docker's granularity, and never fall below it. A percentage above 100 is refused, and so is a bare `cpus: 0` — Docker reads a zero as *uncapped* rather than as none, so it has to be written as `100%` to mean the machine. + +A role that needs the number itself, to size a worker pool or a thread count, reads it with [`lookup('cpus', application_id, '')`](../../plugins/lookup/cpus.py). Reaching for `services..cpus` through `lookup('config', …)` returns the raw text and would size that pool from the string `95%`. + +Two limits: + +- It caps, it does not reserve. Handing one container every CPU removes the backpressure that keeps it from crowding out a parallel deploy, and nothing stops several services from each claiming `100%`. +- The resource budget the `ressources` CLI and the variant lint compute parses `cpus` as a plain float, so a service written as a percentage contributes nothing to that total. + ## License This role is released under the Infinito.Nexus Community License (Non-Commercial) (CNCL). diff --git a/roles/sys-svc-container/templates/deploy.yml.j2 b/roles/sys-svc-container/templates/deploy.yml.j2 index 6d6e6586ce..b14f0dbb51 100644 --- a/roles/sys-svc-container/templates/deploy.yml.j2 +++ b/roles/sys-svc-container/templates/deploy.yml.j2 @@ -40,7 +40,7 @@ condition: {{ docker_restart_policy | default(DOCKER_RESTART_POLICY) | swarm_restart_condition }} resources: limits: - cpus: "{{ lookup('applications') | resource_filter(application_id, 'cpus', service_name | default(''), RESOURCE_CPUS) | string }}" + cpus: "{{ lookup('applications') | resource_filter(application_id, 'cpus', service_name | default(''), RESOURCE_CPUS, host_cpus=RESOURCE_HOST_CPUS) | string }}" memory: {{ lookup('applications') | resource_filter(application_id, 'mem_limit', service_name | default(''), RESOURCE_MEM_LIMIT) }} pids: {{ lookup('applications') | resource_filter(application_id, 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT) }} {% if RUNTIME != 'github' %} diff --git a/roles/sys-svc-container/templates/resource.yml.j2 b/roles/sys-svc-container/templates/resource.yml.j2 index 49fd7a34bf..395c1952af 100644 --- a/roles/sys-svc-container/templates/resource.yml.j2 +++ b/roles/sys-svc-container/templates/resource.yml.j2 @@ -1,4 +1,4 @@ -cpus: {{ lookup('applications') | resource_filter(application_id, 'cpus', service_name | default(''), RESOURCE_CPUS) }} +cpus: {{ lookup('applications') | resource_filter(application_id, 'cpus', service_name | default(''), RESOURCE_CPUS, host_cpus=RESOURCE_HOST_CPUS) }} mem_reservation: {{ lookup('applications') | resource_filter(application_id, 'mem_reservation', service_name | default(''), RESOURCE_MEM_RESERVATION) }} mem_limit: {{ lookup('applications') | resource_filter(application_id, 'mem_limit', service_name | default(''), RESOURCE_MEM_LIMIT) }} pids_limit: {{ lookup('applications') | resource_filter(application_id, 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT) }} diff --git a/roles/web-app-docs/README.md b/roles/web-app-docs/README.md index d5b3f23989..1f2256cc39 100644 --- a/roles/web-app-docs/README.md +++ b/roles/web-app-docs/README.md @@ -38,6 +38,7 @@ Override these keys of `services.docs` in the inventory: | `source_repository` | Repository to document, e.g. a fork | | `fetch_interval` | Seconds between two fetches of new commits and tags | | `build_jobs` | Parallel Sphinx processes per build; raise `cpus` and `mem_limit` with it | +| `cpus` | Container CPU cap; also takes a percentage of the host, e.g. `50%`, see [sys-svc-container](../sys-svc-container/README.md#resource-limits) | ```yaml applications: diff --git a/roles/web-app-peertube/vars/main.yml b/roles/web-app-peertube/vars/main.yml index e26a6cdd19..215da9b801 100644 --- a/roles/web-app-peertube/vars/main.yml +++ b/roles/web-app-peertube/vars/main.yml @@ -11,7 +11,7 @@ PEERTUBE_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enable PEERTUBE_LIVE_ENABLED: "{{ lookup('config', application_id, 'services.peertube.live.enabled') | bool }}" PEERTUBE_RTMP_PORT: "{{ lookup('config', application_id, 'services.peertube.ports.internal.rtmp') }}" -PEERTUBE_CPUS: "{{ lookup('config', application_id, 'services.peertube.cpus') | float }}" +PEERTUBE_CPUS: "{{ lookup('cpus', application_id, 'peertube') | float }}" PEERTUBE_MEM_LIMIT: "{{ lookup('config', application_id, 'services.peertube.mem_limit') }}" PEERTUBE_MAX_OLD_SPACE_SIZE: "{{ lookup('node_max_old_space_size', application_id, entity_name) }}" _peertube_concurrency_candidate: "{{ ((PEERTUBE_CPUS | float) * 0.5) | round(0, 'floor') | int }}" diff --git a/roles/web-app-pretix/templates/env.j2 b/roles/web-app-pretix/templates/env.j2 index 2a8ff4791a..25b8a1a189 100644 --- a/roles/web-app-pretix/templates/env.j2 +++ b/roles/web-app-pretix/templates/env.j2 @@ -15,7 +15,7 @@ PRETIX_DATABASE_HOST={{ lookup('database', application_id, 'host') }} PRETIX_DATABASE_PORT={{ lookup('database', application_id, 'port') }} PRETIX_WEB_CONCURRENCY={{ POSTGRES_ALLOWED_AVG_CONNECTIONS }} PRETIX_WORKER_THREADS={{ (POSTGRES_ALLOWED_AVG_CONNECTIONS | int // 2 ) }} -NUM_WORKERS={{ [2, (2 * (lookup('config', application_id, 'services.pretix.cpus') | float)) | round(0, 'floor') | int] | max }} +NUM_WORKERS={{ [2, (2 * (lookup('cpus', application_id, 'pretix') | float)) | round(0, 'floor') | int] | max }} {% if PRETIX_REDIS_ENABLED %} {% set redis_host = lookup('engine', 'redis', application_id, 'host') %} diff --git a/roles/web-svc-libretranslate/vars/main.yml b/roles/web-svc-libretranslate/vars/main.yml index af16c070d0..1e5d2762e1 100644 --- a/roles/web-svc-libretranslate/vars/main.yml +++ b/roles/web-svc-libretranslate/vars/main.yml @@ -10,7 +10,7 @@ LIBRETRANSLATE_VERSION: "{{ lookup('config', application_id, 'services.libretran LIBRETRANSLATE_LOAD_ONLY: "{{ lookup('config', application_id, 'services.libretranslate.load_only') | join(',') }}" LIBRETRANSLATE_DIRECTIONS: "{{ lookup('config', application_id, 'services.libretranslate.directions') }}" LIBRETRANSLATE_APP_USER: "{{ 'root' if LIBRETRANSLATE_GPU | bool else 'libretranslate' }}" -LIBRETRANSLATE_THREADS: "{{ [(lookup('config', application_id, 'services.libretranslate.cpus') | float) | round(0, 'ceil') | int, 1] | max }}" +LIBRETRANSLATE_THREADS: "{{ [(lookup('cpus', application_id, 'libretranslate') | float) | round(0, 'ceil') | int, 1] | max }}" LIBRETRANSLATE_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'libretranslate') }}" LIBRETRANSLATE_MCP_ENABLED: "{{ lookup('config', application_id, 'services.libretranslatemcp.enabled') | bool }}" LIBRETRANSLATE_MCP_SERVICE_KEY: "libretranslatemcp" diff --git a/tests/unit/python/plugins/filter/test_resource_filter.py b/tests/unit/python/plugins/filter/test_resource_filter.py index c18169ab8e..df4bf92422 100644 --- a/tests/unit/python/plugins/filter/test_resource_filter.py +++ b/tests/unit/python/plugins/filter/test_resource_filter.py @@ -117,6 +117,64 @@ class TestResourceFilter(unittest.TestCase): self.assertEqual(result, 2048) + def test_a_percentage_resolves_against_the_host(self): + """cpus: 100% in services.yml is every CPU the host has.""" + self.mock_get.return_value = "100%" + + result = plugin_module.resource_filter( + self.applications, + self.application_id, + self.key, + service_name="openresty", + hard_default="0.5", + host_cpus=20, + ) + + self.assertEqual(result, 20.0) + + def test_a_percentage_in_the_hard_default_resolves_too(self): + """The share applies to the fallback, not only to an explicit key.""" + self.mock_get.return_value = plugin_module._UNSET + + result = plugin_module.resource_filter( + self.applications, + self.application_id, + self.key, + service_name="openresty", + hard_default="25%", + host_cpus=20, + ) + + self.assertEqual(result, 5.0) + + def test_a_plain_value_is_left_alone(self): + self.mock_get.return_value = "2" + + result = plugin_module.resource_filter( + self.applications, + self.application_id, + self.key, + service_name="openresty", + hard_default="0.5", + host_cpus=20, + ) + + self.assertEqual(result, "2") + + def test_other_keys_keep_a_zero(self): + """Keys other than cpus pass no host_cpus and must keep their zero.""" + self.mock_get.return_value = 0 + + result = plugin_module.resource_filter( + self.applications, + self.application_id, + key="pids_limit", + service_name="openresty", + hard_default=2048, + ) + + self.assertEqual(result, 0) + def test_raises_ansible_filter_error_on_config_errors(self): """Underlying config errors must be wrapped as AnsibleFilterError.""" self.mock_get.side_effect = plugin_module.AppConfigKeyError("bad path") @@ -131,5 +189,55 @@ class TestResourceFilter(unittest.TestCase): ) +class TestResolveCpus(unittest.TestCase): + def test_a_share_of_the_host(self): + for value, expected in ( + ("100%", 20.0), + ("50%", 10.0), + ("25%", 5.0), + (" 10% ", 2.0), + ("2.5%", 0.5), + ): + with self.subTest(value=value): + self.assertEqual(plugin_module.resolve_cpus(value, 20), expected) + + def test_a_full_share_lands_on_the_docker_ceiling(self): + """100% must equal the host count exactly, which is docker's maximum.""" + self.assertEqual(plugin_module.resolve_cpus("100%", 20), 20.0) + + def test_the_host_count_may_arrive_as_a_string(self): + """RESOURCE_HOST_CPUS comes through a lookup and renders as text.""" + self.assertEqual(plugin_module.resolve_cpus("50%", "20"), 10.0) + + def test_a_share_is_rounded_to_dockers_granularity(self): + self.assertEqual(plugin_module.resolve_cpus("33%", 20), 6.6) + self.assertEqual(plugin_module.resolve_cpus("1%", 3), 0.03) + + def test_a_share_never_falls_below_the_smallest_docker_takes(self): + self.assertEqual(plugin_module.resolve_cpus("0%", 20), 0.01) + + def test_a_plain_value_is_returned_unchanged(self): + for value in (2, 0.5, "1.5"): + with self.subTest(value=value): + self.assertEqual(plugin_module.resolve_cpus(value, 20), value) + + def test_a_bare_zero_is_refused_as_uncapped(self): + """docker reads cpus 0 as unlimited, so it must not pass silently.""" + with self.assertRaises(plugin_module.AnsibleFilterError): + plugin_module.resolve_cpus(0, 20) + + def test_more_than_the_host_has_is_refused(self): + with self.assertRaises(plugin_module.AnsibleFilterError): + plugin_module.resolve_cpus("120%", 20) + + def test_an_unreadable_percentage_is_refused(self): + with self.assertRaises(plugin_module.AnsibleFilterError): + plugin_module.resolve_cpus("half%", 20) + + def test_false_is_not_a_zero(self): + """bool is an int in Python, and False here would be a config error.""" + self.assertIs(plugin_module.resolve_cpus(False, 20), False) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_cpus.py b/tests/unit/python/plugins/lookup/test_cpus.py new file mode 100644 index 0000000000..b9db59a0a2 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_cpus.py @@ -0,0 +1,50 @@ +import unittest +from unittest.mock import patch + +from ansible.errors import AnsibleError + +from plugins.lookup.cpus import LookupModule + +VARS = {"application_id": "web-app-docs"} + + +def _run(terms, configured, host_cpus=20): + with ( + patch("plugins.lookup.cpus.ConfigLookup") as config, + patch("plugins.lookup.cpus.ResourceLookup") as resource, + ): + config.return_value.run.return_value = [configured] + resource.return_value.run.return_value = [host_cpus] + result = LookupModule().run(terms, variables=VARS) + return result, config.return_value.run.call_args + + +class TestCpusLookup(unittest.TestCase): + def test_a_percentage_becomes_a_share_of_the_host(self): + result, _ = _run(["web-app-docs", "docs"], "95%") + self.assertEqual(result, [19.0]) + + def test_a_plain_value_passes_through(self): + result, _ = _run(["web-app-docs", "docs"], "2") + self.assertEqual(result, ["2"]) + + def test_the_service_name_builds_the_config_path(self): + _, call = _run(["web-app-hermes", "hermes"], "50%") + self.assertEqual(call.args[0], ["web-app-hermes", "services.hermes.cpus"]) + + @patch("plugins.lookup.cpus.get_entity_name", return_value="docs") + def test_the_entity_name_is_the_default_service(self, _entity): + _, call = _run(["web-app-docs"], "50%") + self.assertEqual(call.args[0], ["web-app-docs", "services.docs.cpus"]) + + def test_no_terms_is_refused(self): + with self.assertRaises(AnsibleError): + LookupModule().run([], variables=VARS) + + def test_a_third_term_is_refused(self): + with self.assertRaises(AnsibleError): + LookupModule().run(["a", "b", "c"], variables=VARS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_webserver_resource.py b/tests/unit/python/plugins/lookup/test_webserver_resource.py new file mode 100644 index 0000000000..034fd00c2f --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_webserver_resource.py @@ -0,0 +1,53 @@ +import unittest +from unittest.mock import patch + +from ansible.errors import AnsibleError + +from plugins.lookup.webserver_resource import PROXY_ROLE, LookupModule + +RESOURCE = {"cpus": "0.5", "pids_limit": 512, "host_cpus": 20} + + +def _run(key, proxy, app, application_id="web-app-docs", service_name=""): + applications = { + PROXY_ROLE: {"services": {"openresty": {key: proxy}}}, + application_id: {"services": {"docs": {key: app}}}, + } + variables = {"application_id": application_id, "service_name": service_name} + with ( + patch("plugins.lookup.webserver_resource.ApplicationsLookup") as apps, + patch("plugins.lookup.webserver_resource.ResourceLookup") as resource, + ): + apps.return_value.run.return_value = [applications] + resource.return_value.run.side_effect = lambda terms, **_k: [RESOURCE[terms[0]]] + return LookupModule().run([key], variables=variables) + + +class TestWebserverResource(unittest.TestCase): + def test_the_tighter_of_the_two_wins(self): + self.assertEqual(_run("cpus", proxy="4", app="2"), [2.0]) + self.assertEqual(_run("cpus", proxy="1", app="2"), [1.0]) + + def test_a_percentage_is_resolved_before_the_comparison(self): + """95% of 20 is 19, so a literal 4 is the tighter of the pair.""" + self.assertEqual(_run("cpus", proxy="4", app="95%"), [4.0]) + + def test_a_percentage_can_be_the_tighter_one(self): + self.assertEqual(_run("cpus", proxy="50%", app="16"), [10.0]) + + def test_pids_limit_stays_an_integer(self): + result = _run("pids_limit", proxy=1024, app=512) + self.assertEqual(result, [512]) + self.assertIsInstance(result[0], int) + + def test_an_unknown_key_is_refused(self): + with self.assertRaises(AnsibleError): + LookupModule().run(["mem_limit"], variables={}) + + def test_more_than_one_term_is_refused(self): + with self.assertRaises(AnsibleError): + LookupModule().run(["cpus", "pids_limit"], variables={}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py b/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py index 21abb48a5e..fc7ddeccfb 100644 --- a/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py +++ b/tests/unit/python/roles/sys-svc-container/test_gpu_runtime.py @@ -16,6 +16,7 @@ BASE = { "application_id": "web-svc-libretranslate", "service_name": "libretranslate", "RESOURCE_CPUS": "1", + "RESOURCE_HOST_CPUS": "8", "RESOURCE_MEM_LIMIT": "1g", "RESOURCE_MEM_RESERVATION": "256m", "RESOURCE_PIDS_LIMIT": "512", @@ -38,7 +39,7 @@ class TestGpuRuntimeRegistration(unittest.TestCase): autoescape=select_autoescape(), ) env.filters["bool"] = _ansible_bool - env.filters["resource_filter"] = lambda _apps, _id, key, _svc, default: ( + env.filters["resource_filter"] = lambda _apps, _id, key, _svc, default, **_k: ( wants_gpu if key == "gpu" else default ) env.globals["lookup"] = lambda name, *a, **k: {} @@ -73,7 +74,7 @@ class TestGpuRuntimeRegistration(unittest.TestCase): autoescape=select_autoescape(), ) env.filters["bool"] = _ansible_bool - env.filters["resource_filter"] = lambda _apps, _id, key, _svc, default: ( + env.filters["resource_filter"] = lambda _apps, _id, key, _svc, default, **_k: ( True if key == "gpu" else default ) env.globals["lookup"] = lambda name, *a, **k: {} diff --git a/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py b/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py index 7438176bf6..6d588c90ae 100644 --- a/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py +++ b/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py @@ -28,6 +28,7 @@ BASE = { "SANDBOX_NODE_LABEL": SANDBOX_LABEL, "DOCKER_RESTART_POLICY": "unless-stopped", "RESOURCE_CPUS": "1", + "RESOURCE_HOST_CPUS": "8", "RESOURCE_MEM_LIMIT": "1g", "RESOURCE_MEM_RESERVATION": "256m", "RESOURCE_PIDS_LIMIT": "512",