From 2e2b42c9b304696545bd0f558d814c051d12ca56 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:16 +0000 Subject: [PATCH 01/19] update(versions): update pins with a declared source (web-app-gitea) --- roles/web-app-gitea/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bf0b9f8563..7b494ca53d 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -112,7 +112,7 @@ giteamcpupstream: enabled: "{{ lookup('config', 'web-app-gitea', 'mcp.enabled') | bool }}" shared: false image: docker.gitea.com/gitea-mcp-server - version: "1.6.0" + version: "1.8.0" update: type: registry_tags image: docker.gitea.com/gitea-mcp-server From 9e1392fc445474f725bdda6c14d394613f5a9661 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:20:40 +0000 Subject: [PATCH 02/19] update(versions): update pins with a declared source (web-app-stalwart) --- roles/web-app-stalwart/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index e9edc177cb..9f0b082711 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -44,7 +44,7 @@ stalwart: placement: manager image: stalwartlabs/stalwart version: "v0.16.25" - webui_version: "v1.0.5" + webui_version: "v1.0.11" update: key: webui_version type: git_tags From 33fdcd1d65f208997274c1378e65a8b4a1682ed5 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:56:14 +0000 Subject: [PATCH 03/19] update(images): update Docker image versions (svc-db-qdrant) --- roles/svc-db-qdrant/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-db-qdrant/meta/services.yml b/roles/svc-db-qdrant/meta/services.yml index 50a5a5fb7c..7b363b9248 100644 --- a/roles/svc-db-qdrant/meta/services.yml +++ b/roles/svc-db-qdrant/meta/services.yml @@ -12,7 +12,7 @@ qdrant: bond: 1 image: qdrant/qdrant name: qdrant - version: v1.19.1 + version: v1.19.2 min_storage: 270MB backup: database_routine: true From a6a6b783938758bfb4643fa5564f77b57bca1d7d Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 19:16:07 +0000 Subject: [PATCH 04/19] update(images): update Docker image versions (svc-ai-ollama) --- roles/svc-ai-ollama/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index 676af6a455..b60dc775cc 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.35.1 + version: 0.40.0 name: ollama min_storage: 3473MB cpus: "4.0" From e203d6f7ab60034a8a2ed3bf67fe7389b62bcf65 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 23:05:26 +0200 Subject: [PATCH 05/19] feat(plugins): size memory parameters from the container limit with one lookup lookup('service_memory_mb', application_id, service_name, share) returns a share of a service's mem_limit in whole MiB. It resolves the limit the way sys-svc-container resolves the container's own: the named service, then the role's primary entity, then RESOURCE_MEM_LIMIT. It replaces the three filters of memory_filters, each with its own unit parser and its own idea of the limit: Redis maxmemory at 0.8 of the limit, and the Confluence and Jira heap at 0.7 and 0.35. The central Redis (409 MiB), Confluence (5734/2867) and Jira (4300/2150) keep their values. A Redis sidecar without a mem_limit of its own does not: the filter fell back to a fixed 256m, which gave 204 MiB, while the lookup takes the limit that container really runs with, the primary entity's. That moves 25 roles to between 409 and 3276 MiB. The heap clamps of the old filters are gone: the 1024 MiB floor, limit minus 1024, the 12288 cap and Xms bounded by mem_reservation. Co-Authored-By: Claude Opus 5.5 (1M context) --- plugins/filter/memory_filters.py | 184 -------------- plugins/lookup/service_memory_mb.py | 106 ++++++++ roles/svc-db-redis/templates/compose.yml.j2 | 2 +- roles/svc-db-redis/templates/service.yml.j2 | 2 +- roles/web-app-confluence/vars/main.yml | 4 +- roles/web-app-jira/vars/main.yml | 4 +- .../plugins/filter/test_memory_filters.py | 234 ------------------ .../plugins/lookup/test_service_memory_mb.py | 101 ++++++++ 8 files changed, 213 insertions(+), 424 deletions(-) delete mode 100644 plugins/filter/memory_filters.py create mode 100644 plugins/lookup/service_memory_mb.py delete mode 100644 tests/unit/python/plugins/filter/test_memory_filters.py create mode 100644 tests/unit/python/plugins/lookup/test_service_memory_mb.py diff --git a/plugins/filter/memory_filters.py b/plugins/filter/memory_filters.py deleted file mode 100644 index e62cdc5df2..0000000000 --- a/plugins/filter/memory_filters.py +++ /dev/null @@ -1,184 +0,0 @@ -from __future__ import annotations - -import re - -from ansible.errors import AnsibleFilterError - -from utils.roles.applications.config import get -from utils.roles.entity.name import get_entity_name - -_UNIT_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([kKmMgGtT]?[bB]?)?\s*$") -_FACTORS = { - "": 1, - "b": 1, - "k": 1024, - "kb": 1024, - "m": 1024**2, - "mb": 1024**2, - "g": 1024**3, - "gb": 1024**3, - "t": 1024**4, - "tb": 1024**4, -} - -# ------------------------------------------------------ -# Helpers: unit conversion -# ------------------------------------------------------ - - -def _to_bytes(v: str) -> int: - """Convert a human-readable size string (e.g., '2g', '512m') to bytes.""" - if v is None: - raise AnsibleFilterError("memory_filters: size value is None") - - s = str(v).strip() - m = _UNIT_RE.match(s) - if not m: - raise AnsibleFilterError(f"memory_filters: invalid size '{v}'") - - num, unit = m.group(1), (m.group(2) or "").lower() - - try: - val = float(num) - except ValueError as e: - raise AnsibleFilterError(f"memory_filters: invalid numeric size '{v}'") from e - - factor = _FACTORS.get(unit) - if factor is None: - raise AnsibleFilterError(f"memory_filters: unknown unit in '{v}'") - - return int(val * factor) - - -def _to_mb(v: str) -> int: - """Convert human-readable size to megabytes.""" - return max(0, _to_bytes(v) // (1024 * 1024)) - - -# ------------------------------------------------------ -# JVM-specific helpers -# ------------------------------------------------------ - - -def _svc(app_id: str) -> str: - """Resolve the internal service name for JVM-based applications.""" - return get_entity_name(app_id) - - -def _mem_limit_mb(apps: dict, app_id: str) -> int: - """Resolve mem_limit for the JVM service of the given application.""" - svc = _svc(app_id) - raw = get(apps, app_id, f"services.{svc}.mem_limit") - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_limit for '{svc}' must be > 0 MB (got '{raw}')" - ) - return mb - - -def _mem_res_mb(apps: dict, app_id: str) -> int: - """Resolve mem_reservation for the JVM service of the given application.""" - svc = _svc(app_id) - raw = get(apps, app_id, f"services.{svc}.mem_reservation") - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_reservation for '{svc}' must be > 0 MB (got '{raw}')" - ) - return mb - - -def jvm_max_mb(apps: dict, app_id: str) -> int: - """ - Compute recommended JVM Xmx in MB using: - Xmx = min( - floor(0.7 * mem_limit), - mem_limit - 1024, - 12288 - ) - with a lower bound of 1024 MB. - """ - limit_mb = _mem_limit_mb(apps, app_id) - c1 = (limit_mb * 7) // 10 - c2 = max(0, limit_mb - 1024) - c3 = 12288 - - return max(1024, min(c1, c2, c3)) - - -def jvm_min_mb(apps: dict, app_id: str) -> int: - """ - Compute recommended JVM Xms in MB using: - Xms = min( - floor(Xmx / 2), - mem_reservation, - Xmx - ) - with a lower bound of 512 MB. - """ - xmx = jvm_max_mb(apps, app_id) - res = _mem_res_mb(apps, app_id) - - return max(512, min(xmx // 2, res, xmx)) - - -# ------------------------------------------------------ -# Redis-specific helpers (always service name "redis") -# ------------------------------------------------------ - - -def _redis_mem_limit_mb(apps: dict, app_id: str, default_mb: int = 256) -> int: - """ - Resolve mem_limit for the Redis service of an application. - Unlike JVM-based services, Redis always uses the service name "redis". - - If no mem_limit is defined, fall back to default_mb. - """ - raw = get( - apps, - app_id, - "services.redis.mem_limit", - strict=False, - default=f"{default_mb}m", - ) - - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_limit for 'redis' must be > 0 MB (got '{raw}')" - ) - - return mb - - -def redis_maxmemory_mb( - apps: dict, app_id: str, factor: float = 0.8, min_mb: int = 64 -) -> int: - """ - Compute recommended Redis `maxmemory` in MB. - - * factor: fraction of allowed memory used for Redis data (default 0.8) - * min_mb: minimum floor value (default 64 MB) - - maxmemory = max(min_mb, floor(factor * mem_limit)) - """ - limit_mb = _redis_mem_limit_mb(apps, app_id) - return max(min_mb, int(limit_mb * factor)) - - -# ------------------------------------------------------ -# Filter module -# ------------------------------------------------------ - - -class FilterModule: - def filters(self): - return { - "jvm_max_mb": jvm_max_mb, - "jvm_min_mb": jvm_min_mb, - "redis_maxmemory_mb": redis_maxmemory_mb, - } diff --git a/plugins/lookup/service_memory_mb.py b/plugins/lookup/service_memory_mb.py new file mode 100644 index 0000000000..2d2f82786e --- /dev/null +++ b/plugins/lookup/service_memory_mb.py @@ -0,0 +1,106 @@ +"""Derive a memory parameter in MiB from the memory limit of a service's container. + + -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}m + memory_limit = {{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M + +The limit is resolved the way ``sys-svc-container`` resolves the container's own +``mem_limit``: ``services..mem_limit``, then the role's primary entity, +then ``RESOURCE_MEM_LIMIT``. ``share`` is the fraction of that limit the +parameter may claim, so a heap, a cache or a per-request limit follows the +container instead of a literal that drifts away from it. + +Sizes are read like Docker reads them: ``k``, ``m`` and ``g`` are binary, a bare +number is bytes. The result is whole MiB, the unit ``-Xmxm``, PHP ``M``, +``memcached -m``, Redis ``mb`` and PostgreSQL ``MB`` all share. +""" + +from __future__ import annotations + +import re +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.filter.resource_filter import resource_filter + +_SIZE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([bkmg]?)b?\s*$", re.IGNORECASE) +_FACTOR = {"": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3} +_MEBIBYTE = 1024**2 +_HOST_DEFAULT = "RESOURCE_MEM_LIMIT" +_UNDECLARED = object() + + +def docker_bytes(size: Any) -> int: + """Return a Docker memory size in bytes. + + Args: + size: a size such as ``2g``, ``1.5g``, ``512m`` or a byte count. + + Raises: + AnsibleError: the size is not a number with an optional b/k/m/g unit. + """ + match = _SIZE.match(str(size)) + if match is None: + raise AnsibleError(f"lookup('service_memory_mb'): unreadable size {size!r}") + return int(float(match.group(1)) * _FACTOR[match.group(2).lower()]) + + +def share_mb(mem_limit: Any, share: Any) -> int: + """Return ``share`` of ``mem_limit`` in whole MiB. + + Args: + mem_limit: Docker size of the container limit, e.g. ``2g`` or ``512m``. + share: fraction of the limit, above 0 and at most 1. + + Raises: + AnsibleError: the share is no fraction in that range, the size is + unreadable, or the result is below 1 MiB. + """ + try: + fraction = float(share) + except (TypeError, ValueError) as exc: + raise AnsibleError( + f"lookup('service_memory_mb'): share {share!r} is not a number" + ) from exc + if not 0 < fraction <= 1: + raise AnsibleError( + f"lookup('service_memory_mb'): share {share!r} must be above 0 and at most 1" + ) + megabytes = int(docker_bytes(mem_limit) * fraction) // _MEBIBYTE + if megabytes < 1: + raise AnsibleError( + f"lookup('service_memory_mb'): {share!r} of {mem_limit!r} is below 1 MiB" + ) + return megabytes + + +class LookupModule(LookupBase): + """lookup('service_memory_mb', application_id, service_name, share)""" + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if len(terms) != 3: + raise AnsibleError( + "lookup('service_memory_mb', application_id, service_name, share) " + "expects exactly 3 positional terms." + ) + application_id, service_name, share = terms + + templar = self._templar + variables = variables or templar.available_variables + applications = lookup_loader.get( + "applications", loader=self._loader, templar=templar + ).run([], variables=variables)[0] + + mem_limit = resource_filter( + applications, application_id, "mem_limit", service_name, _UNDECLARED + ) + if mem_limit is _UNDECLARED: + if _HOST_DEFAULT not in variables: + raise AnsibleError( + f"lookup('service_memory_mb'): '{application_id}' declares no " + f"mem_limit for '{service_name}' and {_HOST_DEFAULT} is unset" + ) + mem_limit = templar.template(variables[_HOST_DEFAULT]) + return [share_mb(mem_limit, share)] diff --git a/roles/svc-db-redis/templates/compose.yml.j2 b/roles/svc-db-redis/templates/compose.yml.j2 index efdbf2ef51..ce32003147 100644 --- a/roles/svc-db-redis/templates/compose.yml.j2 +++ b/roles/svc-db-redis/templates/compose.yml.j2 @@ -10,7 +10,7 @@ exec redis-server --requirepass {{ REDIS_PASSWORD | quote }} --appendonly yes - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int) }}mb + --maxmemory {{ lookup('service_memory_mb', application_id, service_name, 0.8) }}mb --maxmemory-policy allkeys-lru {% include 'roles/sys-svc-container/templates/base.yml.j2' %} diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index e678ee590e..d95e5e21e7 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -13,7 +13,7 @@ - "no" - --save - "" - - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int ) }}mb + - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8) }}mb - --maxmemory-policy - "allkeys-lru" # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does diff --git a/roles/web-app-confluence/vars/main.yml b/roles/web-app-confluence/vars/main.yml index 2ce263f096..180441ce0b 100644 --- a/roles/web-app-confluence/vars/main.yml +++ b/roles/web-app-confluence/vars/main.yml @@ -25,7 +25,7 @@ CONFLUENCE_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_na CONFLUENCE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" CONFLUENCE_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" -CONFLUENCE_JVM_MAX: "{{ lookup('applications') | jvm_max_mb(application_id) }}m" -CONFLUENCE_JVM_MIN: "{{ lookup('applications') | jvm_min_mb(application_id) }}m" +CONFLUENCE_JVM_MAX: "{{ lookup('service_memory_mb', application_id, entity_name, 0.7) }}m" +CONFLUENCE_JVM_MIN: "{{ lookup('service_memory_mb', application_id, entity_name, 0.35) }}m" CONFLUENCE_TRUST_STORE_ENABLED: "{{ lookup('config', application_id, 'services.confluence.truststore_enabled') }}" diff --git a/roles/web-app-jira/vars/main.yml b/roles/web-app-jira/vars/main.yml index 1e5fbc3de4..820d9117fb 100644 --- a/roles/web-app-jira/vars/main.yml +++ b/roles/web-app-jira/vars/main.yml @@ -25,5 +25,5 @@ JIRA_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ ' JIRA_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" JIRA_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" -JIRA_JVM_MAX: "{{ lookup('applications') | jvm_max_mb(application_id) }}m" -JIRA_JVM_MIN: "{{ lookup('applications') | jvm_min_mb(application_id) }}m" +JIRA_JVM_MAX: "{{ lookup('service_memory_mb', application_id, entity_name, 0.7) }}m" +JIRA_JVM_MIN: "{{ lookup('service_memory_mb', application_id, entity_name, 0.35) }}m" diff --git a/tests/unit/python/plugins/filter/test_memory_filters.py b/tests/unit/python/plugins/filter/test_memory_filters.py deleted file mode 100644 index 002eecd3fd..0000000000 --- a/tests/unit/python/plugins/filter/test_memory_filters.py +++ /dev/null @@ -1,234 +0,0 @@ -import importlib -import unittest -from unittest.mock import patch - -memory_filters = importlib.import_module("plugins.filter.memory_filters") - - -class TestMemoryFilters(unittest.TestCase): - def setUp(self): - self.apps = {"whatever": True} - self.app_id = "web-app-confluence" # entity_name will be mocked - - # ----------------------------- - # Helpers - # ----------------------------- - def _with_conf(self, mem_limit: str, mem_res: str): - """ - Patch get/get_entity_name so that mem_limit and mem_reservation - can be controlled in tests. - """ - patches = [ - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - mem_limit - if key.endswith(".mem_limit") - else mem_res - if key.endswith(".mem_reservation") - else None - ), - ), - ] - mocks = [p.start() for p in patches] - self.addCleanup(lambda: [p.stop() for p in patches]) - return mocks - - # ----------------------------- - # Tests: jvm_max_mb / jvm_min_mb sizing - # ----------------------------- - def test_sizing_8g_limit_6g_reservation(self): - self._with_conf("8g", "6g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 5734) - self.assertEqual(xms, 2867) - - def test_sizing_6g_limit_4g_reservation(self): - self._with_conf("6g", "4g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 4300) - self.assertEqual(xms, 2150) - - def test_sizing_16g_limit_12g_reservation_cap_12288(self): - self._with_conf("16g", "12g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 11468) - self.assertEqual(xms, 5734) - - def test_floor_small_limit_results_in_min_1024(self): - self._with_conf("1g", "512m") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - self.assertEqual(xmx, 1024) - - def test_floor_small_reservation_results_in_min_512(self): - self._with_conf("4g", "128m") - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xms, 512) - - # ----------------------------- - # Tests: JVM failure cases / validation - # ----------------------------- - def test_invalid_unit_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8Q" if key.endswith(".mem_limit") else "4g" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_max_mb(self.apps, self.app_id) - - def test_zero_limit_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "0" if key.endswith(".mem_limit") else "4g" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_max_mb(self.apps, self.app_id) - - def test_zero_reservation_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8g" if key.endswith(".mem_limit") else "0" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_min_mb(self.apps, self.app_id) - - def test_entity_name_is_derived_not_passed(self): - """ - Ensure get_entity_name() is called internally and the app_id is not - passed around manually from the template. - """ - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ) as mock_entity, - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8g" if key.endswith(".mem_limit") else "6g" - ), - ), - ): - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertGreater(xmx, 0) - self.assertGreater(xms, 0) - self.assertEqual(mock_entity.call_count, 3) - for call in mock_entity.call_args_list: - self.assertEqual(call.args[0], self.app_id) - - # ----------------------------- - # Tests: redis_maxmemory_mb - # ----------------------------- - def test_redis_maxmemory_default_factor_uses_80_percent_of_limit(self): - self._with_conf("1g", "512m") - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 819) - - def test_redis_maxmemory_custom_factor_and_min_mb(self): - self._with_conf("1g", "512m") - maxmem = memory_filters.redis_maxmemory_mb( - self.apps, - self.app_id, - factor=0.5, - min_mb=128, - ) - self.assertEqual(maxmem, 512) - - def test_redis_maxmemory_honors_minimum_floor(self): - self._with_conf("32m", "16m") - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 64) - - def test_redis_maxmemory_zero_limit_raises(self): - self._with_conf("0", "512m") - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - def test_redis_maxmemory_invalid_unit_raises(self): - self._with_conf("8Q", "512m") - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - def test_redis_maxmemory_does_not_call_get_entity_name(self): - """ - Ensure redis_maxmemory_mb does NOT rely on entity name resolution - (it should always use the hard-coded 'redis' service name). - """ - patches = [ - patch("plugins.filter.memory_filters.get_entity_name"), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "4g" if key.endswith(".mem_limit") else "2g" - ), - ), - ] - mocks = [p.start() for p in patches] - self.addCleanup(lambda: [p.stop() for p in patches]) - - entity_mock = mocks[0] - - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 3276) - entity_mock.assert_not_called() - - def test_redis_maxmemory_uses_default_when_mem_limit_missing(self): - """ - When services.redis.mem_limit is not configured, the filter - should fall back to its internal default (256m). - """ - - def fake_get(apps, app_id, key, required=True, **kwargs): - if key.endswith(".mem_limit"): - return kwargs.get("default") - return None - - with ( - patch( - "plugins.filter.memory_filters.get", - side_effect=fake_get, - ), - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - ): - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - self.assertEqual(maxmem, 204) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_service_memory_mb.py b/tests/unit/python/plugins/lookup/test_service_memory_mb.py new file mode 100644 index 0000000000..d8277c6c11 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_service_memory_mb.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +import unittest +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from plugins.lookup.service_memory_mb import LookupModule, docker_bytes, share_mb + +_APP = "web-app-demo" + + +class TestDockerBytes(unittest.TestCase): + def test_suffixes_are_binary(self) -> None: + self.assertEqual(docker_bytes("512m"), 512 * 1024**2) + self.assertEqual(docker_bytes("2g"), 2 * 1024**3) + self.assertEqual(docker_bytes("1.5g"), 1536 * 1024**2) + self.assertEqual(docker_bytes("64K"), 64 * 1024) + self.assertEqual(docker_bytes("1gb"), 1024**3) + + def test_a_bare_number_is_bytes(self) -> None: + self.assertEqual(docker_bytes(1048576), 1024**2) + self.assertEqual(docker_bytes("2048"), 2048) + + def test_an_unreadable_size_raises(self) -> None: + for size in ("", "lots", "2x", "-1g", None): + with self.subTest(size=size), self.assertRaises(AnsibleError): + docker_bytes(size) + + +class TestShareMb(unittest.TestCase): + def test_share_of_the_limit_in_whole_mebibytes(self) -> None: + cases = ( + ("2g", 0.5, 1024), + ("4g", 0.5, 2048), + ("8g", 0.7, 5734), + ("8g", 0.35, 2867), + ("6g", 0.7, 4300), + ("512m", 0.8, 409), + ("256m", 0.75, 192), + ("1.5g", 0.5, 768), + ("1g", 1, 1024), + ) + for mem_limit, share, expected in cases: + with self.subTest(mem_limit=mem_limit, share=share): + self.assertEqual(share_mb(mem_limit, share), expected) + + def test_a_share_outside_the_limit_raises(self) -> None: + for share in (0, -0.5, 1.01, "half", None): + with self.subTest(share=share), self.assertRaises(AnsibleError): + share_mb("2g", share) + + def test_a_result_below_one_mebibyte_raises(self) -> None: + with self.assertRaises(AnsibleError): + share_mb("1m", 0.5) + + +class TestLookupResolvesTheContainerLimit(unittest.TestCase): + def _run(self, services: dict, variables: dict, terms: list) -> int: + templar = MagicMock() + templar.available_variables = variables + templar.template.side_effect = lambda value: {"{{ HOST }}": "1.5g"}.get( + value, value + ) + applications = MagicMock() + applications.run.return_value = [{_APP: {"services": services}}] + lookup = LookupModule(loader=None, templar=templar) + with patch( + "plugins.lookup.service_memory_mb.lookup_loader.get", + return_value=applications, + ): + return lookup.run(terms, variables=variables)[0] + + def test_the_named_service_wins(self) -> None: + services = {"search": {"mem_limit": "2g"}, "demo": {"mem_limit": "8g"}} + + self.assertEqual(self._run(services, {}, [_APP, "search", 0.5]), 1024) + + def test_the_primary_entity_backs_an_undeclared_service(self) -> None: + services = {"search": {}, "demo": {"mem_limit": "8g"}} + + self.assertEqual(self._run(services, {}, [_APP, "search", 0.5]), 4096) + + def test_the_host_default_backs_an_undeclared_role(self) -> None: + variables = {"RESOURCE_MEM_LIMIT": "{{ HOST }}"} + + self.assertEqual( + self._run({"search": {}}, variables, [_APP, "search", 0.5]), 768 + ) + + def test_no_limit_anywhere_raises(self) -> None: + with self.assertRaises(AnsibleError): + self._run({"search": {}}, {}, [_APP, "search", 0.5]) + + def test_the_term_count_is_checked(self) -> None: + with self.assertRaises(AnsibleError): + self._run({"search": {"mem_limit": "2g"}}, {}, [_APP, "search"]) + + +if __name__ == "__main__": + unittest.main() From 0f7fb92e1270807d77b9976ad0dc874927094bae Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 23:24:22 +0200 Subject: [PATCH 06/19] refactor(roles): take seven roles' memory parameters from the container limit Memcached, Joomla, Moodle, Odoo, Shopware, Snipe-IT and SuiteCRM set their cache size, PHP memory_limit, OPcache, worker limits and search heap as literals next to a mem_limit they never read. They now ask lookup('service_memory_mb') for a share of that limit. The shares are chosen so every rendered value stays what it was. Where the parameter lives in a file that cannot hold a template, the value is handed in: Shopware's init script reads INIT_PHP_MEMORY_LIMIT and refuses to start without it, SuiteCRM's image takes it as a build argument. Shopware's worker gets --memory-limit as a command appended to its entrypoint, and Moodle's OPcache size moves from the static ini into the rendered one. The performance.php.memory_limit keys of Joomla and Moodle are gone from services.yml; nothing else read them. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-db-memcached/templates/compose.yml.j2 | 5 +---- roles/svc-db-memcached/vars/main.yml | 2 +- roles/web-app-joomla/meta/services.yml | 3 --- roles/web-app-joomla/tasks/08_oidc_plugin.yml | 8 ++++---- roles/web-app-joomla/vars/main.yml | 2 +- .../files/build/php-conf/opcache-recommended.ini | 1 - roles/web-app-moodle/meta/services.yml | 1 - .../templates/build/php-conf/moodle-runtime.ini.j2 | 1 + roles/web-app-moodle/vars/main.yml | 2 +- roles/web-app-odoo/templates/odoo.conf.j2 | 4 ++-- roles/web-app-shopware/files/shell/init.sh | 9 +++++---- roles/web-app-shopware/meta/services.yml | 1 - roles/web-app-shopware/templates/compose.yml.j2 | 5 ++++- roles/web-app-shopware/vars/main.yml | 2 +- roles/web-app-snipe-it/tasks/01_install.yml | 2 +- roles/web-app-suitecrm/files/Dockerfile | 5 +++-- roles/web-app-suitecrm/templates/compose.yml.j2 | 1 + roles/web-app-suitecrm/vars/main.yml | 1 + 18 files changed, 27 insertions(+), 28 deletions(-) diff --git a/roles/svc-db-memcached/templates/compose.yml.j2 b/roles/svc-db-memcached/templates/compose.yml.j2 index 1b3883ec84..687ed7e2b7 100644 --- a/roles/svc-db-memcached/templates/compose.yml.j2 +++ b/roles/svc-db-memcached/templates/compose.yml.j2 @@ -3,10 +3,7 @@ {{ service_name }}: {{ lookup('compose_only', 'container_name', MEMCACHED_CONTAINER) }} {{ lookup('container_image', application_id, 'memcached') }} - command: - - "memcached" - - "-m" - - "{{ MEMCACHED_MEMORY_LIMIT_MB }}" + command: ["memcached", "-m", "{{ MEMCACHED_MEMORY_LIMIT_MB }}"] {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {% if MEMCACHED_EXPOSE_LOCAL %} diff --git a/roles/svc-db-memcached/vars/main.yml b/roles/svc-db-memcached/vars/main.yml index 3066f45915..9294151ce2 100644 --- a/roles/svc-db-memcached/vars/main.yml +++ b/roles/svc-db-memcached/vars/main.yml @@ -10,6 +10,6 @@ MEMCACHED_EXPOSE_LOCAL: true MEMCACHED_LOCAL_HOST: "127.0.0.1" MEMCACHED_RETRIES: 5 MEMCACHED_DELAY: 5 -MEMCACHED_MEMORY_LIMIT_MB: 192 +MEMCACHED_MEMORY_LIMIT_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.75) }}" MEMCACHED_EXEC_SHELL: "container exec {{ MEMCACHED_CONTAINER_ADDRESS }} sh -lc" MEMCACHED_PROBE: "printf \"version\\r\\n\" | nc -w 1 {{ MEMCACHED_LOCAL_HOST }} 11211 | grep -q VERSION" diff --git a/roles/web-app-joomla/meta/services.yml b/roles/web-app-joomla/meta/services.yml index 46483ce2ee..282f2caffb 100644 --- a/roles/web-app-joomla/meta/services.yml +++ b/roles/web-app-joomla/meta/services.yml @@ -51,9 +51,6 @@ joomla: no_stop_required: true upload: size_mb: 100 - performance: - php: - memory_limit: 512M autocreate_users: true ports: local: diff --git a/roles/web-app-joomla/tasks/08_oidc_plugin.yml b/roles/web-app-joomla/tasks/08_oidc_plugin.yml index 9c04694812..037239a96c 100644 --- a/roles/web-app-joomla/tasks/08_oidc_plugin.yml +++ b/roles/web-app-joomla/tasks/08_oidc_plugin.yml @@ -53,7 +53,7 @@ - name: "📦 Install plg_system_keycloak via Joomla CLI" ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec --user {{ JOOMLA_WEB_USER | quote }} {{ JOOMLA_LOCAL_CID | quote }} - php -d memory_limit=512M {{ JOOMLA_CLI_FILE | quote }} + php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE | quote }} extension:install --path={{ JOOMLA_OIDC_PLUGIN_ZIP | quote }} register: plugin_install changed_when: "'Extension installed successfully' in plugin_install.stdout" @@ -63,8 +63,8 @@ delegate_to: "{{ JOOMLA_HOST_NODE }}" - name: "🔍 Resolve plg_system_keycloak extension ID" # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - ansible.builtin.shell: "container exec --user {{ JOOMLA_WEB_USER }} {{ JOOMLA_LOCAL_CID | quote }} php -d memory_limit=512M {{ JOOMLA_CLI_FILE }} extension:list - | awk '/plg_system_keycloak/ {print $2; exit}'" + ansible.builtin.shell: "container exec --user {{ JOOMLA_WEB_USER }} {{ JOOMLA_LOCAL_CID | quote }} php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE + }} extension:list | awk '/plg_system_keycloak/ {print $2; exit}'" register: plugin_id_lookup changed_when: false failed_when: plugin_id_lookup.stdout | trim | length == 0 @@ -73,7 +73,7 @@ - name: "🟢 Enable plg_system_keycloak via Joomla CLI" ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec --user {{ JOOMLA_WEB_USER | quote }} {{ JOOMLA_LOCAL_CID | quote }} - php -d memory_limit=512M {{ JOOMLA_CLI_FILE | quote }} + php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE | quote }} extension:enable {{ plugin_id_lookup.stdout | trim | quote }} register: plugin_enable changed_when: "'has been enabled' in plugin_enable.stdout or 'enabled successfully' in plugin_enable.stdout" diff --git a/roles/web-app-joomla/vars/main.yml b/roles/web-app-joomla/vars/main.yml index c7d2ddee5a..a8b0f5d4ae 100644 --- a/roles/web-app-joomla/vars/main.yml +++ b/roles/web-app-joomla/vars/main.yml @@ -23,7 +23,7 @@ JOOMLA_UPLOAD_CONFIG: "{{ [ lookup('container', application_id, 'directories.ins JOOMLA_UPLOAD_SIZE: "{{ lookup('config', application_id, 'services.joomla.upload.size_mb') }}" JOOMLA_UPLOAD_MAX_FILESIZE: "{{ (JOOMLA_UPLOAD_SIZE | int) }}M" JOOMLA_POST_MAX_SIZE: "{{ ((JOOMLA_UPLOAD_SIZE | int) * 12 // 10) }}M" -JOOMLA_PHP_MEMORY_LIMIT: "{{ lookup('config', application_id, 'services.joomla.performance.php.memory_limit') }}" +JOOMLA_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M" JOOMLA_USER_NAME: "{{ lookup('users', 'administrator').username }}" JOOMLA_USER: "{{ JOOMLA_USER_NAME | capitalize }}" diff --git a/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini b/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini index be3fc9f5dc..6271cf8344 100644 --- a/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini +++ b/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini @@ -1,4 +1,3 @@ -opcache.memory_consumption=256 opcache.interned_strings_buffer=16 opcache.max_accelerated_files=20000 opcache.revalidate_freq=60 diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 70f66d0f48..908536fd0f 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -65,7 +65,6 @@ moodle: site_titel: Academy on {{ DOMAIN_PRIMARY }} performance: php: - memory_limit: 512M upload_max_filesize: 256M post_max_size: 256M ports: diff --git a/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 b/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 index 2b8afa62a3..8eb37db7bc 100644 --- a/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 +++ b/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 @@ -1,4 +1,5 @@ memory_limit={{ MOODLE_PHP_MEMORY_LIMIT }} +opcache.memory_consumption={{ lookup('service_memory_mb', application_id, 'moodle', 0.125) }} upload_max_filesize={{ MOODLE_PHP_UPLOAD_MAX_FILESIZE }} post_max_size={{ MOODLE_PHP_POST_MAX_SIZE }} max_execution_time={{ MOODLE_PHP_MAX_EXECUTION_TIME }} diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 786edc0c15..75cfd20cbc 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -130,7 +130,7 @@ MOODLE_SITE_TITLE: "{{ lookup('config', application_id, 'services.moodle.site_ti MOODLE_FPM_PORT: "{{ lookup('config', application_id, 'services.moodle.ports.internal.fpm') }}" MOODLE_NGINX_PORT: "{{ lookup('config', application_id, 'services.moodle.ports.internal.http') }}" -MOODLE_PHP_MEMORY_LIMIT: "{{ lookup('config', application_id, 'services.moodle.performance.php.memory_limit') }}" +MOODLE_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, 'moodle', 0.25) }}M" MOODLE_PHP_UPLOAD_MAX_FILESIZE: "{{ lookup('config', application_id, 'services.moodle.performance.php.upload_max_filesize') }}" MOODLE_PHP_POST_MAX_SIZE: "{{ lookup('config', application_id, 'services.moodle.performance.php.post_max_size') }}" MOODLE_PHP_MAX_EXECUTION_TIME: "300" diff --git a/roles/web-app-odoo/templates/odoo.conf.j2 b/roles/web-app-odoo/templates/odoo.conf.j2 index f1d2487621..71f4837ed4 100644 --- a/roles/web-app-odoo/templates/odoo.conf.j2 +++ b/roles/web-app-odoo/templates/odoo.conf.j2 @@ -28,8 +28,8 @@ gevent_port = {{ container_websocket_port }} proxy_mode = True workers = 4 max_cron_threads = 2 -limit_memory_hard = 2684354560 -limit_memory_soft = 2147483648 +limit_memory_hard = {{ (lookup('service_memory_mb', application_id, 'odoo', 0.625) | int) * 1048576 }} +limit_memory_soft = {{ (lookup('service_memory_mb', application_id, 'odoo', 0.5) | int) * 1048576 }} limit_time_cpu = 600 limit_time_real = 1200 limit_time_real_cron = 600 diff --git a/roles/web-app-shopware/files/shell/init.sh b/roles/web-app-shopware/files/shell/init.sh index 4a7383182a..f758352a92 100644 --- a/roles/web-app-shopware/files/shell/init.sh +++ b/roles/web-app-shopware/files/shell/init.sh @@ -11,6 +11,7 @@ APP_ROOT="/var/www/html" MARKER="$APP_ROOT/.infinito/installed" LOG_PREFIX="[INIT]" PHP_BIN="php" +PHP_MEMORY_LIMIT="${INIT_PHP_MEMORY_LIMIT:?INIT_PHP_MEMORY_LIMIT must be set}" log() { printf "%s %s\n" "$LOG_PREFIX" "$1"; } fail() { printf "%s [ERROR] %s\n" "$LOG_PREFIX" "$1" >&2; exit 1; } @@ -104,18 +105,18 @@ fi if [ "$FIRST_INSTALL" -eq 1 ]; then log "Performing first-time Shopware installation..." - $PHP_BIN -d memory_limit=1024M bin/console system:install --basic-setup --create-database + $PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console system:install --basic-setup --create-database log "Locking the 'admin' account that --basic-setup creates with the published default password..." DEFAULT_ADMIN_PASSWORD="$($PHP_BIN -r 'echo bin2hex(random_bytes(32));')" - $PHP_BIN -d memory_limit=1024M bin/console user:change-password admin \ + $PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console user:change-password admin \ --password="$DEFAULT_ADMIN_PASSWORD" mkdir -p "$(dirname "$MARKER")" : > "$MARKER" fi log "Running database migrations..." -$PHP_BIN -d memory_limit=1024M bin/console database:migrate --all -$PHP_BIN -d memory_limit=1024M bin/console database:migrate-destructive --all +$PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console database:migrate --all +$PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console database:migrate-destructive --all log "Rebuilding caches and assets..." $PHP_BIN bin/console cache:clear diff --git a/roles/web-app-shopware/meta/services.yml b/roles/web-app-shopware/meta/services.yml index 6aeca33839..2e31a7bd76 100644 --- a/roles/web-app-shopware/meta/services.yml +++ b/roles/web-app-shopware/meta/services.yml @@ -99,7 +99,6 @@ worker: - async - low_priority - --time-limit=300 - - --memory-limit=512M cpus: 1.0 mem_reservation: 1g mem_limit: 2g diff --git a/roles/web-app-shopware/templates/compose.yml.j2 b/roles/web-app-shopware/templates/compose.yml.j2 index 7ee84b255d..2f4f6a2497 100644 --- a/roles/web-app-shopware/templates/compose.yml.j2 +++ b/roles/web-app-shopware/templates/compose.yml.j2 @@ -12,6 +12,8 @@ x-environment: &shopware {{ lookup('compose_only', 'container_name', SHOPWARE_INIT_CONTAINER) }} entrypoint: [ "sh", "{{ SHOPWARE_INIT_DOCKER }}" ] user: "0:0" + environment: + INIT_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, service_name, 0.5) }}M" {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} @@ -53,6 +55,7 @@ x-environment: &shopware <<: *shopware {{ lookup('compose_only', 'container_name', SHOPWARE_WORKER_CONTAINER) }} entrypoint: {{ SHOPWARE_WORKER_ENTRYPOINT }} + command: ["--memory-limit={{ lookup('service_memory_mb', application_id, service_name, 0.25) }}M"] {{ lookup('depends_on', {'init': 'service_completed_successfully'}) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} @@ -82,7 +85,7 @@ x-environment: &shopware - discovery.type=single-node - plugins.security.disabled=true - bootstrap.memory_lock=true - - OPENSEARCH_JAVA_OPTS=-Xms{{ SHOPWARE_OPENSEARCH_MEM_RESERVATION }} -Xmx{{ SHOPWARE_OPENSEARCH_MEM_RESERVATION }} + - OPENSEARCH_JAVA_OPTS=-Xms{{ SHOPWARE_OPENSEARCH_HEAP_MB }}m -Xmx{{ SHOPWARE_OPENSEARCH_HEAP_MB }}m ulimits: memlock: { soft: -1, hard: -1 } {{ lookup('depends_on', {'init': 'service_completed_successfully'}) }} diff --git a/roles/web-app-shopware/vars/main.yml b/roles/web-app-shopware/vars/main.yml index a60d6a404d..3a5fedff4a 100644 --- a/roles/web-app-shopware/vars/main.yml +++ b/roles/web-app-shopware/vars/main.yml @@ -44,7 +44,7 @@ SHOPWARE_REDIS_URL: "{{ lookup('engine', 'redis', application_id, 'url') }}" SHOPWARE_OPENSEARCH_PORT: "{{ lookup('config', application_id, 'services.opensearch.ports.internal.http') }}" SHOPWARE_OPENSEARCH_ENABLED: "{{ lookup('config', application_id, 'services.opensearch.enabled') }}" SHOPWARE_OPENSEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.opensearch.name') }}" -SHOPWARE_OPENSEARCH_MEM_RESERVATION: "{{ lookup('config', application_id, 'services.opensearch.mem_reservation') }}" +SHOPWARE_OPENSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'opensearch', 0.5) }}" SHOPWARE_OPENSEARCH_INITIAL_ADMIN_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.opensearch_initial_admin_password') }}" swarm_stack_fatal_grace: 600 diff --git a/roles/web-app-snipe-it/tasks/01_install.yml b/roles/web-app-snipe-it/tasks/01_install.yml index e7dad621e8..ffe2af0b82 100644 --- a/roles/web-app-snipe-it/tasks/01_install.yml +++ b/roles/web-app-snipe-it/tasks/01_install.yml @@ -41,7 +41,7 @@ -e APP_KEY="{{ SNIPE_IT_APP_KEY }}" -e XDG_CONFIG_HOME=/tmp {{ SNIPE_IT_CONTAINER_ADDRESS }} - php -d memory_limit=512M artisan db:seed --force + php -d memory_limit={{ lookup('service_memory_mb', application_id, SNIPE_IT_SERVICE, 0.25) }}M artisan db:seed --force register: snipeit_seed changed_when: "'Seeding:' in snipeit_seed.stdout" failed_when: snipeit_seed.rc != 0 diff --git a/roles/web-app-suitecrm/files/Dockerfile b/roles/web-app-suitecrm/files/Dockerfile index cab3b11d0f..681672774b 100644 --- a/roles/web-app-suitecrm/files/Dockerfile +++ b/roles/web-app-suitecrm/files/Dockerfile @@ -4,6 +4,7 @@ ARG SUITECRM_BASE_VERSION FROM ${SUITECRM_BASE_IMAGE}:${SUITECRM_BASE_VERSION} AS base ARG SUITECRM_APP_DIR +ARG SUITECRM_PHP_MEMORY_LIMIT RUN rm -rf /var/lib/apt/lists/* \ && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y \ @@ -31,11 +32,11 @@ RUN rm -rf /var/lib/apt/lists/* \ ldap \ && rm -rf /var/lib/apt/lists/* -RUN { \ +RUN : "${SUITECRM_PHP_MEMORY_LIMIT:?}" && { \ echo 'file_uploads = On'; \ echo 'upload_max_filesize = 32M'; \ echo 'post_max_size = 32M'; \ - echo 'memory_limit = 512M'; \ + echo "memory_limit = ${SUITECRM_PHP_MEMORY_LIMIT}"; \ } > /usr/local/etc/php/conf.d/suitecrm-upload.ini RUN a2enmod rewrite headers diff --git a/roles/web-app-suitecrm/templates/compose.yml.j2 b/roles/web-app-suitecrm/templates/compose.yml.j2 index d0ce7a9b64..62057023e5 100644 --- a/roles/web-app-suitecrm/templates/compose.yml.j2 +++ b/roles/web-app-suitecrm/templates/compose.yml.j2 @@ -10,6 +10,7 @@ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER }}" SUITECRM_LDAP_EXTENSION_DIR: "{{ SUITECRM_LDAP_EXTENSION_DIR }}" SUITECRM_APP_DIR: "{{ SUITECRM_APP_DIR }}" + SUITECRM_PHP_MEMORY_LIMIT: "{{ SUITECRM_PHP_MEMORY_LIMIT }}" SUITECRM_SEED_DIR: "{{ SUITECRM_SEED_DIR }}" SUITECRM_WEB_USER: "{{ SUITECRM_WEB_USER }}" SUITECRM_WEB_GROUP: "{{ SUITECRM_WEB_GROUP }}" diff --git a/roles/web-app-suitecrm/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index f87c7b5368..fca35e9cd1 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -39,3 +39,4 @@ SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL: "volumes/{{ SUITECRM_ENTRYPOINT_SCRIPT_FILE SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ [ '/usr/local/bin/', SUITECRM_ENTRYPOINT_SCRIPT_FILE ] | path_join }}" SUITECRM_MAX_OLD_SPACE_SIZE: "{{ lookup('node_max_old_space_size', application_id, entity_name) }}" +SUITECRM_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" From a7db89ac0b33677acc956338126f817ffd4d2ae6 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 6 Oct 2026 23:31:14 +0200 Subject: [PATCH 07/19] fix(search): give the search engines half of their container as heap The central Elasticsearch, Zammad's Elasticsearch and Magento's OpenSearch ran with a literal heap beside a mem_limit four times its size: 1g in 4g, 512m in 2g and 512m in 2g. The heap is now half of the limit through lookup('service_memory_mb'), which makes it 2048, 1024 and 1024 MiB and lets it follow the limit when that changes. Xms equals Xmx, so these containers hold that much more memory from the start. Zammad's memcached size and Magento's PHP_MEMORY_LIMIT take the same lookup and keep their values, 256 and 768M. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-db-elasticsearch/templates/env.j2 | 2 +- roles/svc-db-elasticsearch/vars/main.yml | 1 + roles/web-app-magento/templates/compose.yml.j2 | 2 +- roles/web-app-magento/templates/env.j2 | 2 +- roles/web-app-magento/vars/main.yml | 1 + roles/web-app-zammad/templates/compose.yml.j2 | 4 ++-- roles/web-app-zammad/vars/main.yml | 1 + 7 files changed, 8 insertions(+), 5 deletions(-) diff --git a/roles/svc-db-elasticsearch/templates/env.j2 b/roles/svc-db-elasticsearch/templates/env.j2 index 40b5ca2cc8..e3160aa57f 100644 --- a/roles/svc-db-elasticsearch/templates/env.j2 +++ b/roles/svc-db-elasticsearch/templates/env.j2 @@ -6,4 +6,4 @@ xpack.security.enabled=true xpack.security.http.ssl.enabled=false xpack.security.transport.ssl.enabled=false bootstrap.memory_lock=true -ES_JAVA_OPTS=-Xms1g -Xmx1g +ES_JAVA_OPTS=-Xms{{ ELASTICSEARCH_HEAP_MB }}m -Xmx{{ ELASTICSEARCH_HEAP_MB }}m diff --git a/roles/svc-db-elasticsearch/vars/main.yml b/roles/svc-db-elasticsearch/vars/main.yml index af2430a228..874f6021e9 100644 --- a/roles/svc-db-elasticsearch/vars/main.yml +++ b/roles/svc-db-elasticsearch/vars/main.yml @@ -10,6 +10,7 @@ ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'secrets.credential ELASTICSEARCH_EXPOSE_LOCAL: true ELASTICSEARCH_LOCAL_HOST: "127.0.0.1" ELASTICSEARCH_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.elasticsearch.ports.internal.elasticsearch') }}" +ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}" ELASTICSEARCH_RETRIES: 5 ELASTICSEARCH_DELAY: 2 ELASTICSEARCH_API_BASE: "http://{{ ELASTICSEARCH_LOCAL_HOST }}:{{ ELASTICSEARCH_INTERNAL_PORT }}" diff --git a/roles/web-app-magento/templates/compose.yml.j2 b/roles/web-app-magento/templates/compose.yml.j2 index 8ab9ce649d..74e909bc1e 100644 --- a/roles/web-app-magento/templates/compose.yml.j2 +++ b/roles/web-app-magento/templates/compose.yml.j2 @@ -39,7 +39,7 @@ environment: - discovery.type=single-node - plugins.security.disabled=true - - OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m + - OPENSEARCH_JAVA_OPTS=-Xms{{ MAGENTO_SEARCH_HEAP_MB }}m -Xmx{{ MAGENTO_SEARCH_HEAP_MB }}m {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-magento/templates/env.j2 b/roles/web-app-magento/templates/env.j2 index 2de3c20154..e75d1eeab5 100644 --- a/roles/web-app-magento/templates/env.j2 +++ b/roles/web-app-magento/templates/env.j2 @@ -41,6 +41,6 @@ MAGENTO_REMOTE_STORAGE_REGION={{ lookup('objstore', application_id, 'region') }} MAGENTO_REMOTE_STORAGE_PATH_STYLE=1 {% endif %} -PHP_MEMORY_LIMIT=768M +PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'php', 0.75) }}M APACHE_SERVERNAME={{ MAGENTO_DOMAIN }} diff --git a/roles/web-app-magento/vars/main.yml b/roles/web-app-magento/vars/main.yml index d420819050..b251597964 100644 --- a/roles/web-app-magento/vars/main.yml +++ b/roles/web-app-magento/vars/main.yml @@ -19,6 +19,7 @@ MAGENTO_PHP_FPM_CONF_PATH: "{{ [ lookup('container', application_id, 'directorie MAGENTO_OBJSTORE_ENABLED: "{{ lookup('objstore', application_id, 'enabled') }}" MAGENTO_SEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.search.name') }}" +MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}" MAGENTO_PHP_CONTAINER: "{{ lookup('config', application_id, 'services.php.name') }}" MAGENTO_PHP_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'php') }}" diff --git a/roles/web-app-zammad/templates/compose.yml.j2 b/roles/web-app-zammad/templates/compose.yml.j2 index bc0dc5169e..0f22322e40 100644 --- a/roles/web-app-zammad/templates/compose.yml.j2 +++ b/roles/web-app-zammad/templates/compose.yml.j2 @@ -54,7 +54,7 @@ environment: - discovery.type=single-node - xpack.security.enabled=false - - ES_JAVA_OPTS=-Xms512m -Xmx512m + - ES_JAVA_OPTS=-Xms{{ ZAMMAD_SEARCH_HEAP_MB }}m -Xmx{{ ZAMMAD_SEARCH_HEAP_MB }}m {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} @@ -65,7 +65,7 @@ {{ lookup('container_image', 'svc-db-memcached', 'memcached') }} {{ lookup('compose_only', 'container_name', ZAMMAD_MEMCACHED_CONTAINER) }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - command: ["memcached", "-m", "256"] + command: ["memcached", "-m", "{{ lookup('service_memory_mb', application_id, service_name, 0.125) }}"] {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% endif %} diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index ad45a8f4c8..e7fbc345d1 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -22,6 +22,7 @@ ZAMMAD_MEMCACHED_CONTAINER: "{{ lookup('engine', 'memcached', application_id, 'c ZAMMAD_RAILS_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_RAILS_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_WEBSOCKET_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_WEBSOCKET_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_SEARCH_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_SEARCH_SERVICE ~ '.ports.internal.http') }}" +ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.5) }}" # Exception: env.j2 must never set DATABASE_URL. The image's config/pre_initializers/database_url.rb # builds it from POSTGRESQL_* only while DATABASE_URL is blank, so presetting it drops From e6be88bf9714bb768d3c7b406e02476cb5d24ca8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:28:43 +0200 Subject: [PATCH 08/19] fix(postgres): size the buffers from the Postgres container, in its own role shared_buffers, work_mem and maintenance_work_mem were a quarter, half and a twentieth of the host's RAM, while the Postgres container is limited to 6g. On a 64 GB host that asked for 15997 MB of shared buffers inside it. They are now the same shares of the container's mem_limit through lookup('service_memory_mb'): 1536 MB, 3072 MB divided by max_connections, and 307 MB. The three variables move from group_vars/all/17_resource.yml into the role's vars. They no longer describe the host, and only the role's compose template reads them. Their *_MB helpers and POSTGRES_TOTAL_RAM_MB had no other reader and are gone. An inventory can no longer override the three values; the knob is services.postgres.mem_limit. Discourse's db_shared_buffers was a literal 4096MB, all of the 4g the role declares. It becomes a quarter of that limit, 1024MB. It only applies when Discourse runs its bundled database. Co-Authored-By: Claude Opus 5.5 (1M context) --- group_vars/all/17_resource.yml | 7 ------- roles/svc-db-postgres/vars/main.yml | 3 +++ roles/web-app-discourse/templates/config.yml.j2 | 2 +- 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/group_vars/all/17_resource.yml b/group_vars/all/17_resource.yml index 281b5eff75..4392f54ade 100644 --- a/group_vars/all/17_resource.yml +++ b/group_vars/all/17_resource.yml @@ -43,16 +43,9 @@ RESOURCE_MEM_LIMIT: "{{ RESOURCE_MEM_LIMIT_NUM }}g" RESOURCE_PIDS_LIMIT: 512 POSTGRES_VCPUS: "{{ ansible_facts['processor_vcpus'] | int }}" -POSTGRES_TOTAL_RAM_MB: "{{ ansible_facts['memtotal_mb'] | int }}" POSTGRES_MAX_CONNECTIONS: "{{ [ ((POSTGRES_VCPUS | int) * 30 + 50), 400 ] | min }}" POSTGRES_ALLOWED_AVG_CONNECTIONS: "{{ (POSTGRES_MAX_CONNECTIONS | split_postgres_connections(lookup('path_absolute', 'roles'))) | int }}" POSTGRES_SUPERUSER_RESERVED_CONNECTIONS: 3 -POSTGRES_SHARED_BUFFERS_MB: "{{ ((POSTGRES_TOTAL_RAM_MB | int) * 25) // 100 }}" -POSTGRES_SHARED_BUFFERS: "{{ POSTGRES_SHARED_BUFFERS_MB ~ 'MB' }}" -POSTGRES_WORK_MEM_MB: "{{ [ ( (POSTGRES_TOTAL_RAM_MB | int) // ( [ (POSTGRES_MAX_CONNECTIONS | int), 1 ] | max ) // 2 ), 1 ] | max }}" -POSTGRES_WORK_MEM: "{{ POSTGRES_WORK_MEM_MB ~ 'MB' }}" -POSTGRES_MAINTENANCE_WORK_MEM_MB: "{{ [ (((POSTGRES_TOTAL_RAM_MB | int) * 5) // 100), 64 ] | max }}" -POSTGRES_MAINTENANCE_WORK_MEM: "{{ POSTGRES_MAINTENANCE_WORK_MEM_MB ~ 'MB' }}" POSTGRES_MAX_LOCKS_PER_TRANSACTION: 256 POSTGRES_DELAY: 2 diff --git a/roles/svc-db-postgres/vars/main.yml b/roles/svc-db-postgres/vars/main.yml index ab4253a155..b1ff5e62c5 100644 --- a/roles/svc-db-postgres/vars/main.yml +++ b/roles/svc-db-postgres/vars/main.yml @@ -15,3 +15,6 @@ POSTGRES_EXPOSE_LOCAL: true POSTGRES_LOCAL_HOST: "127.0.0.1" POSTGRES_LIBRARIES: "{{ lookup('postgres_libraries', lookup('service_extensions', 'postgres').values() | sum(start=[]) | unique | list) }}" POSTGRES_RETRIES: 5 +POSTGRES_SHARED_BUFFERS: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}MB" +POSTGRES_WORK_MEM: "{{ [ (lookup('service_memory_mb', application_id, entity_name, 0.5) | int) // ([ POSTGRES_MAX_CONNECTIONS | int, 1 ] | max), 1 ] | max }}MB" +POSTGRES_MAINTENANCE_WORK_MEM: "{{ [ lookup('service_memory_mb', application_id, entity_name, 0.05) | int, 64 ] | max }}MB" diff --git a/roles/web-app-discourse/templates/config.yml.j2 b/roles/web-app-discourse/templates/config.yml.j2 index 884d949e89..c72c6c1adc 100644 --- a/roles/web-app-discourse/templates/config.yml.j2 +++ b/roles/web-app-discourse/templates/config.yml.j2 @@ -22,7 +22,7 @@ params: ## Set db_shared_buffers to a max of 25% of the total memory. ## will be set automatically by bootstrap based on detected RAM, or you can override - db_shared_buffers: "4096MB" + db_shared_buffers: "{{ lookup('service_memory_mb', application_id, 'discourse', 0.25) }}MB" ## can improve sorting performance, but adds memory usage per-connection #db_work_mem: "40MB" From 45d956e5eabb6e207a8cdb6a01abb627cf547d51 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:30:01 +0200 Subject: [PATCH 09/19] fix(sidecars): cap an engine's sidecar at its provider's size A Redis sidecar whose consumer declares no services.redis.mem_limit runs in a container that inherits the consumer's primary entity limit. Since the lookup replaced the old filter, maxmemory followed that limit and rose from 204 MiB to between 819 and 3276 MiB in 17 roles. lookup('service_memory_mb', ..., provider=) caps the result at the same share of the provider's own limit when the application does not declare one for that service. A declared limit is not capped, and a container smaller than the provider keeps its own share. The Redis sidecar passes provider='svc-db-redis': those 17 roles get 409 MiB, the seven with a 256 MiB container stay at 204. The lookup now rejects unknown options and a provider that is no role or declares no limit for the service, so a misspelled option fails instead of silently lifting the cap. The memcached sidecar's literal -m 64 takes the same lookup and keeps its value. Co-Authored-By: Claude Opus 5.5 (1M context) --- plugins/lookup/service_memory_mb.py | 49 +++++++++- .../svc-db-memcached/templates/service.yml.j2 | 5 +- roles/svc-db-redis/README.md | 2 +- roles/svc-db-redis/templates/service.yml.j2 | 2 +- .../plugins/lookup/test_service_memory_mb.py | 95 ++++++++++++++++++- 5 files changed, 140 insertions(+), 13 deletions(-) diff --git a/plugins/lookup/service_memory_mb.py b/plugins/lookup/service_memory_mb.py index 2d2f82786e..bc7ab9975c 100644 --- a/plugins/lookup/service_memory_mb.py +++ b/plugins/lookup/service_memory_mb.py @@ -1,6 +1,6 @@ """Derive a memory parameter in MiB from the memory limit of a service's container. - -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}m + -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.25) }}m memory_limit = {{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M The limit is resolved the way ``sys-svc-container`` resolves the container's own @@ -9,6 +9,15 @@ then ``RESOURCE_MEM_LIMIT``. ``share`` is the fraction of that limit the parameter may claim, so a heap, a cache or a per-request limit follows the container instead of a literal that drifts away from it. +A sidecar that a provider role ships into other stacks passes ``provider``: + + --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8, provider='svc-db-redis') }}mb + +An application that declares no ``mem_limit`` for that service lets its container +inherit the primary entity's, which is sized for the application and not for the +engine beside it. The result is then capped at the same share of the provider's +own limit. An application that declares the limit itself is not capped. + Sizes are read like Docker reads them: ``k``, ``m`` and ``g`` are binary, a bare number is bytes. The result is whole MiB, the unit ``-Xmxm``, PHP ``M``, ``memcached -m``, Redis ``mb`` and PostgreSQL ``MB`` all share. @@ -24,6 +33,11 @@ from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase from plugins.filter.resource_filter import resource_filter +from utils.roles.applications.config import ( + AppConfigKeyError, + ConfigEntryNotSetError, + get, +) _SIZE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([bkmg]?)b?\s*$", re.IGNORECASE) _FACTOR = {"": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3} @@ -77,7 +91,7 @@ def share_mb(mem_limit: Any, share: Any) -> int: class LookupModule(LookupBase): - """lookup('service_memory_mb', application_id, service_name, share)""" + """lookup('service_memory_mb', application_id, service_name, share[, provider=role])""" def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): if len(terms) != 3: @@ -86,6 +100,12 @@ class LookupModule(LookupBase): "expects exactly 3 positional terms." ) application_id, service_name, share = terms + unknown = sorted(set(kwargs) - {"provider"}) + if unknown: + raise AnsibleError( + f"lookup('service_memory_mb'): unknown option(s) {unknown}; " + "the only option is provider=" + ) templar = self._templar variables = variables or templar.available_variables @@ -103,4 +123,27 @@ class LookupModule(LookupBase): f"mem_limit for '{service_name}' and {_HOST_DEFAULT} is unset" ) mem_limit = templar.template(variables[_HOST_DEFAULT]) - return [share_mb(mem_limit, share)] + megabytes = share_mb(mem_limit, share) + + if "provider" in kwargs: + if not kwargs["provider"] or not isinstance(kwargs["provider"], str): + raise AnsibleError( + "lookup('service_memory_mb'): provider must name a role" + ) + own = f"services.{service_name}.mem_limit" + try: + ceiling = get(applications, kwargs["provider"], own, False, _UNDECLARED) + inherited = ( + get(applications, application_id, own, False, _UNDECLARED) + is _UNDECLARED + ) + except (AppConfigKeyError, ConfigEntryNotSetError) as exc: + raise AnsibleError(f"lookup('service_memory_mb'): {exc}") from exc + if ceiling is _UNDECLARED: + raise AnsibleError( + f"lookup('service_memory_mb'): provider {kwargs['provider']!r} " + f"declares no mem_limit for '{service_name}'" + ) + if inherited: + megabytes = min(megabytes, share_mb(ceiling, share)) + return [megabytes] diff --git a/roles/svc-db-memcached/templates/service.yml.j2 b/roles/svc-db-memcached/templates/service.yml.j2 index cf91ec5014..257b24f783 100644 --- a/roles/svc-db-memcached/templates/service.yml.j2 +++ b/roles/svc-db-memcached/templates/service.yml.j2 @@ -5,10 +5,7 @@ {{ lookup('compose_restart') }} logging: driver: journald - command: - - memcached - - -m - - "64" + command: ["memcached", "-m", "{{ lookup('service_memory_mb', application_id, 'memcached', 0.25, provider='svc-db-memcached') }}"] # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does healthcheck: # nocheck: healthcheck-timing-override, healthcheck-start-period-covers-interval a swarm-init gate that must clear in seconds, so it runs without a start window rather than inside one test: ["CMD-SHELL", "printf 'version\\r\\n' | nc -w 1 127.0.0.1 11211 | grep -q VERSION"] diff --git a/roles/svc-db-redis/README.md b/roles/svc-db-redis/README.md index 6a4f203290..70b1588070 100644 --- a/roles/svc-db-redis/README.md +++ b/roles/svc-db-redis/README.md @@ -18,7 +18,7 @@ The central stack (`templates/compose.yml.j2`) runs `redis:alpine` with: Per-consumer provisioning (`tasks/01_init.yml`) runs with `application_id=svc-db-redis` and `database_consumer_id=`; it resolves the consumer's username, password and key-prefix via `lookup('engine', 'redis', , ...)` and reconciles an idempotent `ACL SETUSER` restricted to `~{entity}:*`. The ACL users are recreated by the consumer's `01_init` on every deploy, so a container restart that drops the in-memory ACL set is healed on the next run. -The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. +The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. Its `maxmemory` is 80 % of the consumer's `services.redis.mem_limit`; a consumer that declares none gets 80 % of the limit its container inherits, at most 80 % of this role's own `mem_limit`. ## Cosmos diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index d95e5e21e7..8bc3775856 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -13,7 +13,7 @@ - "no" - --save - "" - - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8) }}mb + - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8, provider='svc-db-redis') }}mb - --maxmemory-policy - "allkeys-lru" # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does diff --git a/tests/unit/python/plugins/lookup/test_service_memory_mb.py b/tests/unit/python/plugins/lookup/test_service_memory_mb.py index d8277c6c11..152eba62ed 100644 --- a/tests/unit/python/plugins/lookup/test_service_memory_mb.py +++ b/tests/unit/python/plugins/lookup/test_service_memory_mb.py @@ -8,6 +8,7 @@ from ansible.errors import AnsibleError from plugins.lookup.service_memory_mb import LookupModule, docker_bytes, share_mb _APP = "web-app-demo" +_PROVIDER = "svc-db-cache" class TestDockerBytes(unittest.TestCase): @@ -55,22 +56,36 @@ class TestShareMb(unittest.TestCase): share_mb("1m", 0.5) -class TestLookupResolvesTheContainerLimit(unittest.TestCase): - def _run(self, services: dict, variables: dict, terms: list) -> int: +class _LookupCase(unittest.TestCase): + def _run( + self, + services: dict, + variables: dict, + terms: list, + provided: dict | None = None, + **kwargs, + ) -> int: templar = MagicMock() templar.available_variables = variables templar.template.side_effect = lambda value: {"{{ HOST }}": "1.5g"}.get( value, value ) applications = MagicMock() - applications.run.return_value = [{_APP: {"services": services}}] + applications.run.return_value = [ + { + _APP: {"services": services}, + _PROVIDER: {"services": provided or {}}, + } + ] lookup = LookupModule(loader=None, templar=templar) with patch( "plugins.lookup.service_memory_mb.lookup_loader.get", return_value=applications, ): - return lookup.run(terms, variables=variables)[0] + return lookup.run(terms, variables=variables, **kwargs)[0] + +class TestLookupResolvesTheContainerLimit(_LookupCase): def test_the_named_service_wins(self) -> None: services = {"search": {"mem_limit": "2g"}, "demo": {"mem_limit": "8g"}} @@ -97,5 +112,77 @@ class TestLookupResolvesTheContainerLimit(unittest.TestCase): self._run({"search": {"mem_limit": "2g"}}, {}, [_APP, "search"]) +class TestProviderCapsAnInheritedLimit(_LookupCase): + def _sidecar( + self, + services: dict, + provided: dict | None = None, + share: float = 0.8, + variables: dict | None = None, + **kwargs, + ) -> int: + if provided is None: + provided = {"cache": {"mem_limit": "512m"}} + return self._run( + services, + variables or {}, + [_APP, "cache", share], + provided=provided, + **(kwargs or {"provider": _PROVIDER}), + ) + + def test_an_inherited_limit_is_capped_at_the_providers(self) -> None: + for inherited, expected in (("4g", 409), ("1g", 409), ("512m", 409)): + with self.subTest(inherited=inherited): + self.assertEqual( + self._sidecar({"demo": {"mem_limit": inherited}}), expected + ) + + def test_a_small_inherited_limit_stays_below_its_own_container(self) -> None: + self.assertEqual(self._sidecar({"demo": {"mem_limit": "256m"}}), 204) + + def test_the_cap_uses_the_share_of_the_call(self) -> None: + self.assertEqual(self._sidecar({"demo": {"mem_limit": "4g"}}, share=0.25), 128) + + def test_the_host_default_is_capped_as_well(self) -> None: + variables = {"RESOURCE_MEM_LIMIT": "{{ HOST }}"} + + self.assertEqual(self._sidecar({}, variables=variables), 409) + + def test_a_declared_limit_is_not_capped(self) -> None: + services = {"cache": {"mem_limit": "1g"}, "demo": {"mem_limit": "4g"}} + + self.assertEqual(self._sidecar(services), 819) + + def test_a_provider_without_a_limit_raises_even_when_nothing_is_capped( + self, + ) -> None: + for services in ( + {"demo": {"mem_limit": "4g"}}, + {"cache": {"mem_limit": "1g"}}, + ): + with self.subTest(services=services), self.assertRaises(AnsibleError): + self._sidecar(services, provided={"cache": {}}) + + def test_only_the_providers_limit_for_that_very_service_counts(self) -> None: + with self.assertRaises(AnsibleError): + self._run( + {"demo": {"mem_limit": "4g"}}, + {}, + [_APP, "store", 0.8], + provided={"cache": {"mem_limit": "512m"}}, + provider=_PROVIDER, + ) + + def test_a_provider_that_is_no_role_raises(self) -> None: + for provider in ("", None, "svc-db-missing"): + with self.subTest(provider=provider), self.assertRaises(AnsibleError): + self._sidecar({"cache": {"mem_limit": "1g"}}, provider=provider) + + def test_a_misspelled_option_raises(self) -> None: + with self.assertRaises(AnsibleError): + self._sidecar({"demo": {"mem_limit": "4g"}}, providr=_PROVIDER) + + if __name__ == "__main__": unittest.main() From 3fb237a1432ee56b1d88d03eb480f0cc384e960f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:32:05 +0200 Subject: [PATCH 10/19] fix(search): keep the search heaps at the size they had The heaps of the central Elasticsearch, Zammad's Elasticsearch and Magento's OpenSearch follow their container through the lookup, so far at half of the limit. That doubled them to 2048, 1024 and 1024 MiB. Xms equals Xmx, so each container claims that heap from its start, and the central one locks it in memory. A quarter of the limit gives 1024, 512 and 512 MiB, the sizes these engines ran with before. The heap still follows the limit. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/svc-db-elasticsearch/vars/main.yml | 2 +- roles/web-app-magento/vars/main.yml | 2 +- roles/web-app-zammad/vars/main.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/roles/svc-db-elasticsearch/vars/main.yml b/roles/svc-db-elasticsearch/vars/main.yml index 874f6021e9..39e44dc3c0 100644 --- a/roles/svc-db-elasticsearch/vars/main.yml +++ b/roles/svc-db-elasticsearch/vars/main.yml @@ -10,7 +10,7 @@ ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'secrets.credential ELASTICSEARCH_EXPOSE_LOCAL: true ELASTICSEARCH_LOCAL_HOST: "127.0.0.1" ELASTICSEARCH_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.elasticsearch.ports.internal.elasticsearch') }}" -ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}" +ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}" ELASTICSEARCH_RETRIES: 5 ELASTICSEARCH_DELAY: 2 ELASTICSEARCH_API_BASE: "http://{{ ELASTICSEARCH_LOCAL_HOST }}:{{ ELASTICSEARCH_INTERNAL_PORT }}" diff --git a/roles/web-app-magento/vars/main.yml b/roles/web-app-magento/vars/main.yml index b251597964..ce391fede0 100644 --- a/roles/web-app-magento/vars/main.yml +++ b/roles/web-app-magento/vars/main.yml @@ -19,7 +19,7 @@ MAGENTO_PHP_FPM_CONF_PATH: "{{ [ lookup('container', application_id, 'directorie MAGENTO_OBJSTORE_ENABLED: "{{ lookup('objstore', application_id, 'enabled') }}" MAGENTO_SEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.search.name') }}" -MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.5) }}" +MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.25) }}" MAGENTO_PHP_CONTAINER: "{{ lookup('config', application_id, 'services.php.name') }}" MAGENTO_PHP_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'php') }}" diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index e7fbc345d1..c74ff2bb10 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -22,7 +22,7 @@ ZAMMAD_MEMCACHED_CONTAINER: "{{ lookup('engine', 'memcached', application_id, 'c ZAMMAD_RAILS_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_RAILS_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_WEBSOCKET_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_WEBSOCKET_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_SEARCH_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_SEARCH_SERVICE ~ '.ports.internal.http') }}" -ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.5) }}" +ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.25) }}" # Exception: env.j2 must never set DATABASE_URL. The image's config/pre_initializers/database_url.rb # builds it from POSTGRESQL_* only while DATABASE_URL is blank, so presetting it drops From 333c9fe6d784bc47b74450b8ad5ffadf33e16d9e Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:32:57 +0200 Subject: [PATCH 11/19] fix(web-app-snipe-it): take LDAP_MEM_LIM from the container limit LDAP_MEM_LIM was a literal 500M beside a 2g container. It is now a quarter of the service's mem_limit through lookup('service_memory_mb'), the share the seed command of this role already uses. That renders 512M. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-snipe-it/templates/env.j2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-snipe-it/templates/env.j2 b/roles/web-app-snipe-it/templates/env.j2 index 4814df58e9..a725042808 100644 --- a/roles/web-app-snipe-it/templates/env.j2 +++ b/roles/web-app-snipe-it/templates/env.j2 @@ -148,5 +148,5 @@ APP_LOCKED=false APP_CIPHER=AES-256-CBC APP_FORCE_TLS={{ lookup('tls', application_id, 'enabled') | string | lower }} GOOGLE_MAPS_API= -LDAP_MEM_LIM=500M +LDAP_MEM_LIM={{ lookup('service_memory_mb', application_id, SNIPE_IT_SERVICE, 0.25) }}M LDAP_TIME_LIM=600 From 462bc4ccf013dbb100f40ca8af2923846fea0d53 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:37:17 +0200 Subject: [PATCH 12/19] fix(web-app-shopware): keep the init memory limit in the role's env file The init service received INIT_PHP_MEMORY_LIMIT through an inline environment block in the compose template. It moves to templates/env.j2, which the container base hands to every Shopware container as env_file. Only files/shell/init.sh reads the variable, behind a `:?` guard, so the other containers seeing it changes nothing. The lookup names 'init' instead of service_name, which is bound in the compose template but not in env.j2. The value stays 1024M. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-shopware/templates/compose.yml.j2 | 2 -- roles/web-app-shopware/templates/env.j2 | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/roles/web-app-shopware/templates/compose.yml.j2 b/roles/web-app-shopware/templates/compose.yml.j2 index 2f4f6a2497..e3867b9f80 100644 --- a/roles/web-app-shopware/templates/compose.yml.j2 +++ b/roles/web-app-shopware/templates/compose.yml.j2 @@ -12,8 +12,6 @@ x-environment: &shopware {{ lookup('compose_only', 'container_name', SHOPWARE_INIT_CONTAINER) }} entrypoint: [ "sh", "{{ SHOPWARE_INIT_DOCKER }}" ] user: "0:0" - environment: - INIT_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, service_name, 0.5) }}M" {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-shopware/templates/env.j2 b/roles/web-app-shopware/templates/env.j2 index f0cbf7103c..99b6e59b08 100644 --- a/roles/web-app-shopware/templates/env.j2 +++ b/roles/web-app-shopware/templates/env.j2 @@ -11,6 +11,7 @@ TRUSTED_PROXIES={{ ([networks.internet.values() | select | list, NETWORK_TRUSTED TRUSTED_HOSTS={{ SHOPWARE_DOMAIN }} DATABASE_URL=mysql://{{ lookup('database', application_id, 'username') }}:{{ lookup('database', application_id, 'password') }}@{{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }}/{{ lookup('database', application_id, 'name') }} +INIT_PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'init', 0.5) }}M {% if SHOPWARE_REDIS_ENABLED | bool %} REDIS_URL={{ SHOPWARE_REDIS_URL }}/0 From ba5c4b0060c17413a924c031ce2c561c1b2c0fc8 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:38:12 +0200 Subject: [PATCH 13/19] docs(atlassian): describe the heap as a share of the container limit The Confluence and Jira READMEs said the JVM heap was derived from host RAM with safe caps. It is 70 % of the service's mem_limit for JVM_MAXIMUM_MEMORY and 35 % for JVM_MINIMUM_MEMORY, and the caps of the old filter no longer exist. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-confluence/README.md | 4 ++-- roles/web-app-jira/README.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/roles/web-app-confluence/README.md b/roles/web-app-confluence/README.md index 390ac319d6..d92f4d1a65 100644 --- a/roles/web-app-confluence/README.md +++ b/roles/web-app-confluence/README.md @@ -6,7 +6,7 @@ Confluence is Atlassian’s enterprise wiki and collaboration platform. This rol ## Overview -The role builds a minimal custom image on top of the official Confluence image, prepares persistent volumes, and exposes the app behind your reverse proxy. Configuration is driven by variables (image, version, volumes, domains, OIDC). JVM heap sizing is auto-derived from host RAM with safe caps to avoid `Xms > Xmx`. +The role builds a minimal custom image on top of the official Confluence image, prepares persistent volumes, and exposes the app behind your reverse proxy. Configuration is driven by variables (image, version, volumes, domains, OIDC). JVM heap sizing follows the container's `mem_limit`: `JVM_MAXIMUM_MEMORY` is 70 % of it and `JVM_MINIMUM_MEMORY` 35 %. ## Cosmos @@ -60,7 +60,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( * **Reverse-Proxy Ready:** Sets `ATL_PROXY_NAME/PORT/SCHEME/SECURE` so Confluence generates correct external URLs behind HTTPS. * **OIDC SSO (Optional):** Pre-templated vars for issuer, client, scopes, JWKS; compatible with Atlassian DC SSO/OIDC marketplace apps. * **Central Database:** PostgreSQL integration (local or central DB) with bootstrap credentials from role vars. -* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` computed from host memory with upper bounds. +* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` are 35 % and 70 % of the service `mem_limit`. * **Health Checks:** Curl-based container healthcheck for early failure detection. * **CSP & Canonical Domains:** Hooks into platform CSP/SSL/domain management to keep policies strict and URLs stable. * **Backup Friendly:** Data isolated under `{{ CONFLUENCE_HOME }}`. diff --git a/roles/web-app-jira/README.md b/roles/web-app-jira/README.md index 0614a6a212..552a6756be 100644 --- a/roles/web-app-jira/README.md +++ b/roles/web-app-jira/README.md @@ -6,7 +6,7 @@ ## Overview -The role builds a lean custom image on top of the official Jira Software image, provisions persistent volumes, and exposes the app behind your reverse proxy. Variables control image/version/volumes/domains/SSO. JVM heap sizing is auto-derived from host RAM with safe caps to prevent `Xms > Xmx`. +The role builds a lean custom image on top of the official Jira Software image, provisions persistent volumes, and exposes the app behind your reverse proxy. Variables control image/version/volumes/domains/SSO. JVM heap sizing follows the container's `mem_limit`: `JVM_MAXIMUM_MEMORY` is 70 % of it and `JVM_MINIMUM_MEMORY` 35 %. ## Cosmos @@ -60,7 +60,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( * **Reverse-Proxy/HTTPS Ready:** Preconfigured Atlassian Tomcat proxy envs so Jira respects external scheme/host/port. * **OIDC SSO (Optional):** Pre-templated vars for issuer, client, endpoints, scopes; compatible with Atlassian DC SSO/OIDC marketplace apps. * **Central Database:** PostgreSQL integration (local or central) with credentials sourced from role configuration. -* **JVM Auto-Tuning:** Safe calculation of `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` with caps to avoid VM init errors. +* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` are 35 % and 70 % of the service `mem_limit`. * **Health Checks:** Container healthcheck for quicker failure detection and stable automation. * **CSP & Canonical Domains:** Integrates with platform CSP and domain management. * **Backup Ready:** Persistent data under `{{ JIRA_STORAGE_PATH }}`. From b56b0551aaf8c97d1d4ecbc7fb593e3631988d48 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:40:20 +0200 Subject: [PATCH 14/19] fix(web-app-wordpress): size PHP's memory_limit from the container, not the upload upload.ini set memory_limit to WORDPRESS_MAX_UPLOAD_SIZE, the same 256M as upload_max_filesize and post_max_size, so the memory a request may use depended on how large an upload may be. It is now a quarter of the service's mem_limit through lookup('service_memory_mb'), which renders 384M beside the 1.5g container. The upload sizes keep their variable. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-wordpress/templates/upload.ini.j2 | 2 +- roles/web-app-wordpress/vars/main.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/roles/web-app-wordpress/templates/upload.ini.j2 b/roles/web-app-wordpress/templates/upload.ini.j2 index a14ff008b0..e02d303ec0 100644 --- a/roles/web-app-wordpress/templates/upload.ini.j2 +++ b/roles/web-app-wordpress/templates/upload.ini.j2 @@ -1,5 +1,5 @@ file_uploads = On -memory_limit = {{ WORDPRESS_MAX_UPLOAD_SIZE }} +memory_limit = {{ WORDPRESS_PHP_MEMORY_LIMIT }} upload_max_filesize = {{ WORDPRESS_MAX_UPLOAD_SIZE }} post_max_size = {{ WORDPRESS_MAX_UPLOAD_SIZE }} max_execution_time = 300 diff --git a/roles/web-app-wordpress/vars/main.yml b/roles/web-app-wordpress/vars/main.yml index eac46649e7..8e384834a0 100644 --- a/roles/web-app-wordpress/vars/main.yml +++ b/roles/web-app-wordpress/vars/main.yml @@ -5,6 +5,7 @@ entity_name: "{{ application_id | get_entity_name }}" WORDPRESS_URL: "{{ lookup('tls', application_id, 'url.base') }}" WORDPRESS_TITLE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.title') }}" WORDPRESS_MAX_UPLOAD_SIZE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.max_upload_size') }}" +WORDPRESS_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" WORDPRESS_DOCKER_HTML_PATH: "{{ lookup('volume', 'web-app-wordpress', 'data').target }}" WORDPRESS_DOCKER_CONF_PATH: "{{ WORDPRESS_CONFIG_PATH }}" WORDPRESS_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" From 1f72f59ec15616aa63bde9d915db69af6c93f5bb Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:41:55 +0200 Subject: [PATCH 15/19] fix(web-app-nextcloud): size PHP's memory from the container, not the host PHP_MEMORY_LIMIT and PHP_OPCACHE_MEMORY_CONSUMPTION were both the host's RAM divided by 30, read from two keys in meta/services.yml: 533M on a 16 GB host, 2133M on a 64 GB one, beside a container limited to 3g either way. They are now half and an eighth of that limit through lookup('service_memory_mb'), which renders 1536M and 384M on every host. The lookup sits in env.j2 and the two meta keys are gone. It reads the applications payload, and meta/services.yml is part of that payload, so a call from there would run back into the render that asked for it. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-nextcloud/meta/services.yml | 2 -- roles/web-app-nextcloud/templates/env.j2 | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 13f7f4b47e..6e0d032d02 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -84,9 +84,7 @@ nextcloud: enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'services.sso.enabled') | bool) }}" performance: php: - memory_limit: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" upload_limit: 5G - opcache_memory_consumption: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" fpm: max_children: 16 start_servers: 4 diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index e63e181507..523629cb98 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -5,9 +5,9 @@ MYSQL_USER={{ lookup('database', application_id, 'username') }} MYSQL_PASSWORD={{ lookup('database', application_id, 'password') | dotenv_quote }} MYSQL_HOST={{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }} -PHP_MEMORY_LIMIT={{ lookup('config', application_id, 'services.nextcloud.performance.php.memory_limit') }} +PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'nextcloud', 0.5) }}M PHP_UPLOAD_LIMIT={{ lookup('config', application_id, 'services.nextcloud.performance.php.upload_limit') }} -PHP_OPCACHE_MEMORY_CONSUMPTION={{ lookup('config', application_id, 'services.nextcloud.performance.php.opcache_memory_consumption') }} +PHP_OPCACHE_MEMORY_CONSUMPTION={{ lookup('service_memory_mb', application_id, 'nextcloud', 0.125) }}M {% set email = lookup('email', application_id) %} {% if email.enabled | bool %} From f4b5b7be252fbf578bd971cca35cc9ee839b1796 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:43:25 +0200 Subject: [PATCH 16/19] test(lint): require memory parameters to follow the container limit A heap, a cache size or a PHP limit written as a literal drifts away from the mem_limit its service declares. The lint scans roles/ and group_vars/ for the known spellings of such parameters and requires each value to reach lookup('service_memory_mb'), or the Node lookup for the V8 heap, on its own line or through the variables it reads. It follows names inside {{ }} and $NAME through the definitions of the role and of group_vars, reads a command list, a folded scalar and a wrapped expression as one line, and counts a literal fallback as a literal. A sidecar snippet has to name its own role as provider. It knows a list of spellings and layouts. A parameter written another way is not seen. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../test_memory_parameters_use_lookup.py | 546 ++++++++++++++++++ 1 file changed, 546 insertions(+) create mode 100644 tests/lint/ansible/services/test_memory_parameters_use_lookup.py diff --git a/tests/lint/ansible/services/test_memory_parameters_use_lookup.py b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py new file mode 100644 index 0000000000..70a725928d --- /dev/null +++ b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py @@ -0,0 +1,546 @@ +"""Lint guard: a known memory parameter MUST follow the container's memory limit. + +A heap, a cache size or a per-request limit written as a literal drifts away +from the ``mem_limit`` its service declares in ``meta/services.yml``: raising +the limit leaves the parameter behind, lowering it lets the process outgrow its +container. Every parameter in ``PARAMETERS`` therefore has to reach +``lookup('service_memory_mb', ...)``, or ``lookup('node_max_old_space_size', ...)`` +for the V8 heap. + +The lookup may sit on the parameter's own line or behind the variables its value +reads. A value reads the names inside its ``{{ }}`` expressions, apart from string +literals, attribute access and filters, and its ``$NAME`` / ``${NAME}`` shell +references. Indirection is followed inside the role and ``group_vars``: a name +counts when one of its definitions (``NAME: value``, ``NAME=value``, +``{% set NAME = value %}``) reaches the lookup, however many names lie between. +A value that keeps a literal fallback (``${NAME:-512M}``, ``... else 512``, +``default(512)``) does not count. + +Only a value that starts like a size is a parameter: a digit, ``{{`` or ``$``. +That leaves prose, probes and the unlimited markers ``-1`` and ``0`` alone. A +block list under ``command:``, ``entrypoint:``, ``argv:``, ``args:`` or ``cmd:``, +a folded scalar, a backslash continuation and an expression wrapped over several +lines are each read as one line, so a flag and its value may be apart. + +A sidecar snippet (``roles//templates/service.yml.j2``) runs in another +role's stack. Its lookups MUST pass ``provider=''``, which keeps the size of +an engine from following the limit of the application it sits beside. + +The scan knows the spellings in ``PARAMETERS`` and the layouts above. A parameter +written another way is not seen; add its spelling when a role introduces one. +""" + +from __future__ import annotations + +import re +import subprocess +import unittest +from bisect import bisect_right +from collections import defaultdict +from functools import cache +from typing import TYPE_CHECKING, ClassVar + +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, Sequence + +_SEPARATOR = r"""[\]"']*\s*(?:=>?|:|,)?\s*(?:>[+-]?\s+)?(?:value:\s*)?["'\s]*""" +PARAMETERS = ( + r"-Xm[snx]", + r"-XX:(?:Max|Initial)HeapSize=", + r"-XX:MaxDirectMemorySize=", + r"\b\w*HEAP_SIZE" + _SEPARATOR, + r"\b\w*M(?:AX|IN)(?:IMUM)?_MEMORY" + _SEPARATOR, + r"(?i:memory[-_]limit)" + _SEPARATOR, + r"\bwgMemoryLimit" + _SEPARATOR, + r"(?i:memory_consumption)" + _SEPARATOR, + r"\bLDAP_MEM_LIM" + _SEPARATOR, + r"\blimit[-_]memory[-_](?:hard|soft)" + _SEPARATOR, + r"\bmaxmemory" + _SEPARATOR, + r"\bmemcached\b[^&|;]*?[\s\"']-m" + _SEPARATOR, + r"(?(?=\d|\{\{|\$)(?:\{\{.*?\}\}|\$\{[^}]*\}|\S)+)" +) +_UNLIMITED = re.compile(r"0(?![\w.])") +_LOOKUP = re.compile( + r"(?:lookup|query)\(\s*['\"](?:service_memory_mb|node_max_old_space_size)['\"]" +) +_FALLBACK = re.compile(r"\$\{\w+:-\s*[\"']?\d|\belse\s+[\"']?\d|\bdefault\(\s*[\"']?\d") +_EXPRESSION = re.compile(r"\{\{(.*?)\}\}", re.DOTALL) +_NOT_A_NAME = re.compile(r"'[^']*'|\"[^\"]*\"|\.\s*[A-Za-z_]\w*|\|\s*[A-Za-z_]\w*") +_NAME = re.compile(r"[A-Za-z_]\w*") +_SHELL_NAME = re.compile(r"\$\{?([A-Za-z_]\w*)") +_DEFINITION = re.compile( + r"^\s*(?:-\s+)?(?:(?:export|local|readonly|ARG|ENV)\s+)?" + r"[\"']?([A-Za-z_]\w*)[\"']?\s*(?::(?=\s|$)|=)(.*)$" +) +_JINJA_SET = re.compile(r"\{%-?\s*set\s+(\w+)\s*=(.*?)-?%\}") +_BLOCK_SCALAR = re.compile(r"[>|][+-]?\d*") +_ARGV_KEY = re.compile(r"^\s*(?:-\s+)?(?:command|entrypoint|argv|args|cmd)\s*:\s*$") +_FOLDED = re.compile(r":\s*>[+-]?\d*\s*$") +_ITEM = re.compile(r"^\s*-\s+") +_TRAILING_COMMENT = re.compile(r"\s#.*$") +_SIDECAR = re.compile(r"roles/([^/]+)/templates/service\.yml\.j2") +_SIZING = re.compile(r"lookup\(\s*['\"]service_memory_mb['\"][^)]*\)") +_COMMENT = ("#", ";", "//", "{#") +_SHARED_SCOPE = "group_vars" +_WRAP = 20 + + +def _indent(line: str) -> int: + return len(line) - len(line.lstrip()) + + +def _code(lines: Sequence[str]) -> list[str]: + return [_TRAILING_COMMENT.sub("", line) for line in lines] + + +def _open(lines: Sequence[str]) -> bool: + return sum(line.count("{{") for line in lines) > sum( + line.count("}}") for line in lines + ) + + +def _block_end(lines: Sequence[str], start: int) -> int: + end = start + 1 + while end < len(lines) and ( + not lines[end].strip() or _indent(lines[end]) > _indent(lines[start]) + ): + end += 1 + return end + + +def definitions(lines: Sequence[str]) -> Iterator[tuple[str, str]]: + """Yield every ``(name, value)`` a file defines. + + Args: + lines: the file's lines. Trailing comments are cut. A value continues over + the deeper indented lines below its key when it is a YAML block scalar + or leaves a ``{{`` open. + """ + lines = _code(lines) + for number, line in enumerate(lines): + for name, expression in _JINJA_SET.findall(line): + yield name, "{{" + expression + "}}" + match = _DEFINITION.match(line) + if not match: + continue + value = match[2] + if _BLOCK_SCALAR.fullmatch(value.strip()) or _open([value]): + value = " ".join([value, *lines[number + 1 : _block_end(lines, number)]]) + yield match[1], value + + +def references(value: str) -> set[str]: + """Return the names *value* reads. + + Args: + value: text that is rendered later. Names inside ``{{ }}`` and shell + references count; bare words, string literals, attributes and + filters do not. + """ + names = set(_SHELL_NAME.findall(value)) + for expression in _EXPRESSION.findall(value): + names.update(_NAME.findall(_NOT_A_NAME.sub(" ", expression))) + return names + + +def reaches_lookup(value: str, known: Mapping[str, Sequence[str]]) -> bool: + """Whether *value* calls the lookup itself or reads a variable that does. + + Args: + value: the expression a parameter is set to. + known: variable name to every value it is defined with. + """ + pending, seen = [value], set() + while pending: + current = pending.pop() + if _FALLBACK.search(current): + continue + if _LOOKUP.search(current): + return True + for name in references(current) - seen: + seen.add(name) + pending.extend(known.get(name, ())) + return False + + +def _logical_lines(lines: Sequence[str]) -> Iterator[tuple[str, list[int], list[int]]]: + """Yield ``(text, offsets, numbers)``: one logical line and where each source line starts in it. + + Args: + lines: the file's lines, trailing comments already cut. + """ + index = 0 + while index < len(lines): + end = index + 1 + if _ARGV_KEY.match(lines[index]) or _FOLDED.search(lines[index]): + end = _block_end(lines, index) + while ( + end < len(lines) + and end - index < _WRAP + and (lines[end - 1].rstrip().endswith("\\") or _open(lines[index:end])) + ): + end += 1 + text, offsets, numbers = "", [], [] + for number in range(index, end): + piece = lines[number] + if number > index: + piece = _ITEM.sub("", piece).strip() + if piece.startswith(_COMMENT): + continue + offsets.append(len(text)) + numbers.append(number + 1) + text += piece.rstrip("\\") + " " + yield text, offsets, numbers + index = end + + +def parameters(text: str) -> list[tuple[int, str, str]]: + """Return ``(line number, parameter with value, value)`` per known parameter. + + Args: + text: a file's content. Comments and the unlimited marker ``0`` are skipped. + """ + found = [] + for line, offsets, numbers in _logical_lines(_code(text.splitlines())): + if line.lstrip().startswith(_COMMENT): + continue + for match in _PARAMETER.finditer(line): + if not _UNLIMITED.match(match.group("value")): + number = numbers[bisect_right(offsets, match.start()) - 1] + found.append((number, match.group(0), match.group("value"))) + return found + + +def detached(text: str, known: Mapping[str, Sequence[str]]) -> list[tuple[int, str]]: + """Return ``(line number, parameter with value)`` for every parameter that never reaches the lookup. + + Args: + text: a file's content. + known: variable name to every value it is defined with. + """ + return [ + (number, parameter) + for number, parameter, value in parameters(text) + if not reaches_lookup(value, known) + ] + + +def unprovided(rel: str, text: str) -> list[int]: + """Return the lines of a sidecar snippet whose lookup does not name its own role as provider. + + Args: + rel: repository-relative path of the file. + text: its content. + """ + sidecar = _SIDECAR.fullmatch(rel) + if not sidecar: + return [] + provider = re.compile(rf"provider\s*=\s*['\"]{re.escape(sidecar[1])}['\"]") + return [ + number + for number, line in enumerate(text.splitlines(), 1) + for call in _SIZING.findall(line) + if not provider.search(call) + ] + + +def merged(*scopes: Mapping[str, Sequence[str]]) -> dict[str, list[str]]: + """Return one name-to-values map holding every definition of every scope. + + Args: + scopes: name-to-values maps; a name defined in several keeps all its values. + """ + union: dict[str, list[str]] = defaultdict(list) + for scope in scopes: + for name, values in scope.items(): + union[name].extend(values) + return union + + +def _scope(rel: str) -> str: + parts = rel.split("/") + return "/".join(parts[:2]) if parts[0] == "roles" else _SHARED_SCOPE + + +@cache +def _tracked_texts() -> dict[str, str]: + out = subprocess.check_output( + [ + "git", + "-c", + "safe.directory=*", + "-C", + str(PROJECT_ROOT), + "ls-files", + "roles", + _SHARED_SCOPE, + ], + text=True, + ) + texts: dict[str, str] = {} + for rel in out.splitlines(): + if rel.endswith(".md"): + continue + try: + texts[rel] = read_text(str(PROJECT_ROOT / rel)) + except (OSError, UnicodeDecodeError): + continue + return texts + + +class TestMemoryParametersUseLookup(unittest.TestCase): + def test_every_memory_parameter_follows_the_container_limit(self) -> None: + texts = _tracked_texts() + index: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list)) + for rel, text in texts.items(): + for name, value in definitions(text.splitlines()): + index[_scope(rel)][name].append(value) + known = { + scope: merged(*(index[name] for name in {_SHARED_SCOPE, scope})) + for scope in list(index) + } + + seen = 0 + offenders: list[str] = [] + for rel, text in sorted(texts.items()): + seen += len(parameters(text)) + offenders.extend( + f" {rel}:{number}: {parameter}" + for number, parameter in detached(text, known.get(_scope(rel), {})) + ) + + self.assertGreater(seen, 0, "the scan matched no memory parameter at all") + self.assertFalse( + offenders, + "Memory parameters that do not follow their container's mem_limit " + f"({len(offenders)}):\n" + + "\n".join(offenders) + + "\n\nSet the value with lookup('service_memory_mb', application_id, " + ", ), directly or through a variable of the role.", + ) + + def test_every_sidecar_lookup_names_its_provider(self) -> None: + texts = _tracked_texts() + sized = sum( + len(_SIZING.findall(text)) + for rel, text in texts.items() + if _SIDECAR.fullmatch(rel) + ) + offenders = [ + f" {rel}:{number}" + for rel, text in sorted(texts.items()) + for number in unprovided(rel, text) + ] + + self.assertGreater(sized, 0, "no sidecar snippet sizes memory with the lookup") + self.assertFalse( + offenders, + "Sidecar lookups without provider='':\n" + "\n".join(offenders), + ) + + +class TestResolution(unittest.TestCase): + _SIZED: ClassVar[str] = "{{ lookup('service_memory_mb', 'app', 'php', 0.5) }}" + + def test_literal_is_reported(self) -> None: + self.assertEqual( + detached("ES_JAVA_OPTS=-Xms512m -Xmx512m", {}), + [(1, "-Xms512m"), (1, "-Xmx512m")], + ) + + def test_literal_next_to_a_resolved_value_is_still_reported(self) -> None: + self.assertEqual( + detached("ES_JAVA_OPTS=-Xms512m -Xmx{{ HEAP }}m", {"HEAP": [self._SIZED]}), + [(1, "-Xms512m")], + ) + + def test_direct_lookup_passes(self) -> None: + self.assertEqual(detached(f"memory_limit = {self._SIZED}M", {}), []) + + def test_chain_of_variables_passes(self) -> None: + known = dict( + definitions( + [ + 'PHP_LIMIT="${INIT_LIMIT:?INIT_LIMIT must be set}"', + " INIT_LIMIT: \"{{ ROLE_LIMIT ~ 'M' }}\"", + "ROLE_LIMIT: >-", + " {{ lookup('service_memory_mb', application_id, 'init', 0.5) }}", + ] + ) + ) + self.assertEqual( + detached( + 'php -d memory_limit="$PHP_LIMIT" bin/console', + {k: [v] for k, v in known.items()}, + ), + [], + ) + + def test_variable_that_never_reaches_the_lookup_is_reported(self) -> None: + known = {"A": ["{{ B }}"], "B": ["{{ A }}"], "OTHER": ["512M"]} + self.assertEqual( + detached("--maxmemory {{ A }}mb\nshared_buffers={{ OTHER }}", known), + [(1, "maxmemory {{ A }}mb"), (2, "shared_buffers={{ OTHER }}")], + ) + + def test_a_name_inside_a_string_literal_is_not_followed(self) -> None: + sized = [self._SIZED] + known = {"config": sized, "limit": sized, "int": sized, "item": ["512M"]} + value = "{{ lookup('config', item.limit, 'php.limit') | int }}" + self.assertEqual( + detached(f"PHP_MEMORY_LIMIT={value}", known), + [(1, f"MEMORY_LIMIT={value}")], + ) + + def test_a_literal_fallback_does_not_count(self) -> None: + known = {"INIT": [self._SIZED]} + for line in ( + 'PHP_MEMORY_LIMIT="${INIT:-1024M}"', + "-Xmx{{ INIT if swarm else 512 }}m", + "memory_limit = {{ INIT | default(512) }}M", + ): + with self.subTest(line=line): + self.assertEqual(len(detached(line, known)), 1) + + def test_a_lookup_named_in_a_comment_does_not_count(self) -> None: + known = { + name: [value] + for name, value in definitions( + ["HEAP: 1024 # lookup('service_memory_mb', ...) rounds too low"] + ) + } + self.assertEqual(detached("-Xmx{{ HEAP }}m", known), [(1, "-Xmx{{ HEAP }}m")]) + + def test_a_role_definition_does_not_hide_the_shared_one(self) -> None: + known = merged({"SIZE": [self._SIZED]}, {"SIZE": ["{{ SIZE }}"]}) + self.assertEqual(detached("work_mem={{ SIZE }}", known), []) + + def test_flag_and_value_apart_are_one_parameter(self) -> None: + sized = {"SIZE": [self._SIZED]} + for block, line in ( + ( + ' command:\n - memcached\n - -m\n - "{{ SIZE }}"\n image: x', + 2, + ), + ( + ' argv:\n - redis-server\n - "--maxmemory"\n - "{{ SIZE }}mb"', + 3, + ), + ('command: ["redis-server", "--maxmemory", "{{ SIZE }}mb"]', 1), + ("shell: >-\n redis-server\n --maxmemory\n {{ SIZE }}mb", 3), + ("exec memcached \\\n -m {{ SIZE }} \\\n -p 11211", 1), + ): + with self.subTest(block=block): + self.assertEqual(detached(block, sized), []) + self.assertEqual( + [number for number, _ in detached(block, {"SIZE": ["64"]})], [line] + ) + + def test_a_value_wrapped_over_lines_is_one_value(self) -> None: + wrapped = ( + "X_MEMORY_LIMIT: \"{{ [ (lookup('service_memory_mb', application_id,\n" + " 'php', 0.5) | int), 64 ] | max }}M\"" + ) + for text in (wrapped, f"X_MEMORY_LIMIT: >-\n {self._SIZED}M"): + with self.subTest(text=text): + self.assertEqual(len(parameters(text)), 1) + self.assertEqual(detached(text, {}), []) + self.assertEqual(len(detached("X_MEMORY_LIMIT: >-\n 512M", {})), 1) + + def test_every_spelling_of_a_parameter_is_known(self) -> None: + for line in ( + "php_admin_value[memory_limit] = 1G", + "php_value memory_limit 512M", + "@ini_set('memory_limit', '512M');", + "'memory_limit' => '512M',", + '"memory_limit": "512M",', + '- { key: "WP_MEMORY_LIMIT", value: "256M" }', + '$wgMemoryLimit = "512M";', + "JVM_MAXIMUM_MEMORY: 4096m", + "JICOFO_MAX_MEMORY=3072m", + "ES_HEAP_SIZE=1g", + "JAVA_OPTS=-XX:MaxHeapSize=7g", + "JAVA_OPTS=-Xmn256m", + "LDAP_MEM_LIM=500M", + " - --memory-limit=512M", + 'command: ["--memory-limit", "512M"]', + "opcache.memory_consumption=256", + "limit_memory_hard = 2684354560", + "odoo --limit-memory-hard 2684354560", + ' db_shared_buffers: "4096MB"', + ' - "effective_cache_size=4GB"', + ' - "--innodb-buffer-pool-size=1G"', + "NODE_OPTIONS=--max-old-space-size=4096", + ): + with self.subTest(line=line): + self.assertEqual(len(detached(line, {})), 1) + + def test_unrelated_lines_are_ignored(self) -> None: + for line in ( + " # -Xmx512m", + "; memory_limit = 512M", + "- --maxmemory-policy allkeys-lru", + "- --maxmemory 0", + 'RUN : "${PHP_MEMORY_LIMIT:?}"', + "bootstrap.memory_lock=true", + "mem_limit: 2g", + "network_mem: 512", + "php -d memory_limit=-1 artisan migrate", + "RUN COMPOSER_MEMORY_LIMIT=-1 composer install", + ' - "autovacuum_work_mem=-1"', + "retries: 3 # was php -d memory_limit=512M", + "retries: 3 #was php -d memory_limit=512M", + '- name: "Tune the JVM heap (-Xms/-Xmx)"', + "php -i | grep -E '^memory_limit => '", + 'f"--max-old-space-size={megabytes}"', + "memcached && install -m 0755 /src /dst", + ): + with self.subTest(line=line): + self.assertEqual(detached(line, {}), []) + + +class TestSidecarProvider(unittest.TestCase): + _SNIPPET: ClassVar[str] = "roles/svc-db-redis/templates/service.yml.j2" + + def _line(self, options: str) -> str: + return ( + " - --maxmemory {{ lookup('service_memory_mb', application_id, " + f"'redis', 0.8{options}) }}}}mb" + ) + + def test_a_sidecar_lookup_without_its_own_provider_is_reported(self) -> None: + for options in ( + "", + ", provider='svc-db-memcached'", + ", providr='svc-db-redis'", + ): + with self.subTest(options=options): + self.assertEqual(unprovided(self._SNIPPET, self._line(options)), [1]) + + def test_a_sidecar_lookup_naming_its_role_passes(self) -> None: + line = self._line(", provider='svc-db-redis'") + + self.assertEqual(unprovided(self._SNIPPET, line), []) + + def test_other_files_are_not_sidecars(self) -> None: + path = f"roles/svc-db-redis/{ROLE_FILE_TEMPL_COMPOSE}" + + self.assertEqual(unprovided(path, self._line("")), []) + + +if __name__ == "__main__": + unittest.main() From 9413aeba0894a1d2bb19b2124ee8f570ba26397f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 7 Oct 2026 01:50:21 +0200 Subject: [PATCH 17/19] fix(web-app-gitea): give the MCP sidecar a healthcheck that can run gitea-mcp-server 1.8.0 is the first release that ships a HEALTHCHECK, and it is written in shell form for an image that has no shell. Every probe ends in 'exec: "/bin/sh": no such file or directory', the container turns unhealthy after three attempts, and Swarm replaces the task about every 72 seconds, so the service never converges. The role now declares the probe itself, in exec form and with the port the sidecar listens on: without it the probe asks 8080 whatever the server uses. The command took that port from the adapter's entry, it now reads the sidecar's own. The adapter waits for a healthy sidecar, so a probe that cannot pass fails a compose deploy as well and not only a Swarm one. Co-Authored-By: Claude Opus 5.5 (1M context) --- roles/web-app-gitea/meta/services.yml | 7 +++++++ roles/web-app-gitea/templates/compose.yml.j2 | 2 ++ roles/web-app-gitea/vars/main.yml | 2 +- 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index 7b494ca53d..9b353e76c4 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -117,6 +117,13 @@ giteamcpupstream: type: registry_tags image: docker.gitea.com/gitea-mcp-server name: gitea-mcp + healthcheck: + test: + - "CMD" + - "/app/gitea-mcp" + - "-healthcheck" + - "--port" + - "{{ lookup('config', 'web-app-gitea', 'services.giteamcpupstream.ports.internal.http') | string }}" cpus: 0.25 mem_reservation: 0.1g mem_limit: 0.25g diff --git a/roles/web-app-gitea/templates/compose.yml.j2 b/roles/web-app-gitea/templates/compose.yml.j2 index 2e56345b14..8ebf840c08 100644 --- a/roles/web-app-gitea/templates/compose.yml.j2 +++ b/roles/web-app-gitea/templates/compose.yml.j2 @@ -28,6 +28,7 @@ GITEA_HOST: "{{ GITEA_MCP_UPSTREAM_URL }}" GITEA_SCOPES: "{{ GITEA_MCP_TOOL_SCOPES }}" GITEA_READONLY: "true" + {{ lookup('container_healthcheck', service_name) | indent(4) }} networks: # nocheck: networks-literal the sidecar authenticates nobody, so it joins the private upstream net and nothing else {{ GITEA_MCP_UPSTREAM_NETWORK }}: {{ lookup('depends_on', {'gitea': 'service_healthy'}) }} @@ -55,6 +56,7 @@ ADAPTER_PORT: "{{ GITEA_MCP_PORT }}" expose: - "{{ GITEA_MCP_PORT }}" + {{ lookup('depends_on', {GITEA_MCP_SIDECAR_SERVICE_KEY: 'service_healthy'}) }} {{ lookup('container_healthcheck', 'giteamcp') | indent(4) }} {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {{ GITEA_MCP_UPSTREAM_NETWORK }}: diff --git a/roles/web-app-gitea/vars/main.yml b/roles/web-app-gitea/vars/main.yml index 50fb563bdf..7b36c9e8e4 100644 --- a/roles/web-app-gitea/vars/main.yml +++ b/roles/web-app-gitea/vars/main.yml @@ -62,7 +62,7 @@ GITEA_MCP_COMMAND: - "-t" - "http" - "--port" - - "{{ GITEA_MCP_PORT | string }}" + - "{{ GITEA_MCP_SIDECAR_PORT | string }}" - "-r" GITEA_MCP_INITIALIZE_PAYLOAD: jsonrpc: "2.0" From 426ab1ea2a2e81617cb0e43881c18693f45a9113 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:16:03 +0000 Subject: [PATCH 18/19] update(images): update Docker image versions (svc-db-elasticsearch) --- roles/svc-db-elasticsearch/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/svc-db-elasticsearch/meta/services.yml b/roles/svc-db-elasticsearch/meta/services.yml index 6f13b566e6..d40ab5fa1d 100644 --- a/roles/svc-db-elasticsearch/meta/services.yml +++ b/roles/svc-db-elasticsearch/meta/services.yml @@ -12,7 +12,7 @@ elasticsearch: bond: 1 image: elasticsearch name: elasticsearch - version: "9.5.3" + version: "9.5.5" min_storage: 1066MB backup: database_routine: true From eecdeecb9f5d174d60b252a2123f36e363d12f63 Mon Sep 17 00:00:00 2001 From: "infinito-nexus-updater[bot]" <286144613+infinito-nexus-updater[bot]@users.noreply.github.com> Date: Wed, 7 Oct 2026 00:16:10 +0000 Subject: [PATCH 19/19] update(images): update Docker image versions (web-app-gitea) --- roles/web-app-gitea/meta/services.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bf0b9f8563..5700465d75 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -49,7 +49,7 @@ gitea: shared: true provides: gitea image: gitea/gitea - version: 28.0.0 + version: 28.1.0 replicas: 1 # nocheck: single-replica single-writer app state on swarm-shared NFS; concurrent multi-node writers corrupt app.ini min_storage: 270MB backup: