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/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..bc7ab9975c --- /dev/null +++ b/plugins/lookup/service_memory_mb.py @@ -0,0 +1,149 @@ +"""Derive a memory parameter in MiB from the memory limit of a service's container. + + -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 +``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. + +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. +""" + +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 +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} +_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[, provider=role])""" + + 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 + 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 + 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]) + 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-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" 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 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..39e44dc3c0 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.25) }}" ELASTICSEARCH_RETRIES: 5 ELASTICSEARCH_DELAY: 2 ELASTICSEARCH_API_BASE: "http://{{ ELASTICSEARCH_LOCAL_HOST }}:{{ ELASTICSEARCH_INTERNAL_PORT }}" 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/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-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/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/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 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/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..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('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int ) }}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/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-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-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" diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bf0b9f8563..ac35951047 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: @@ -112,11 +112,18 @@ 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 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" 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 }}`. 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/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-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..ce391fede0 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.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-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-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 %} 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..e3867b9f80 100644 --- a/roles/web-app-shopware/templates/compose.yml.j2 +++ b/roles/web-app-shopware/templates/compose.yml.j2 @@ -53,6 +53,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 +83,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/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 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-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 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 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" 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') }}" diff --git a/roles/web-app-zammad/templates/compose.yml.j2 b/roles/web-app-zammad/templates/compose.yml.j2 index 344af9b7ff..1891a8514c 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 - path.data={{ ZAMMAD_SEARCH_DATA_DIR }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} @@ -66,7 +66,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 5edd2392dd..8263ec6910 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.25) }}" ZAMMAD_SEARCH_MAJOR: "{{ (lookup('config', application_id, 'services.search.version') | string).split('.') | first }}" ZAMMAD_SEARCH_DATA_DIR: "{{ [lookup('volume', application_id, 'zammad_search').target, ZAMMAD_SEARCH_MAJOR] | path_join }}" 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() 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..152eba62ed --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_service_memory_mb.py @@ -0,0 +1,188 @@ +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" +_PROVIDER = "svc-db-cache" + + +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 _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}, + _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, **kwargs)[0] + + +class TestLookupResolvesTheContainerLimit(_LookupCase): + 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"]) + + +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()