diff --git a/cli/build/docs/readme/generate.py b/cli/build/docs/readme/generate.py index 201362567f..40b6b7c780 100644 --- a/cli/build/docs/readme/generate.py +++ b/cli/build/docs/readme/generate.py @@ -44,9 +44,10 @@ def _is_invokable(role_name: str) -> bool: def _render_template(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 โ€” renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(schema.TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(schema.TEMPLATE_NAME).render(**ctx) diff --git a/cli/build/docs/readme/schema.py b/cli/build/docs/readme/schema.py index dc66b8ea89..ca7a3b3c47 100644 --- a/cli/build/docs/readme/schema.py +++ b/cli/build/docs/readme/schema.py @@ -42,9 +42,10 @@ _OPTIONAL_CTX: dict = { def _render(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 โ€” renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(TEMPLATE_NAME).render(**ctx) 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-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md index cfd9b2bf62..2d0d4d4bc3 100644 --- a/roles/svc-ai-mcp-adapter/README.md +++ b/roles/svc-ai-mcp-adapter/README.md @@ -26,6 +26,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Client-facing authentication:** The adapter issues its own bearer. The upstream credential authenticates the adapter to the provider and says nothing about who called the adapter, which is the gap the project-owned MCP sidecars leave open. - **Allowlist on `tools/call`:** Filtering only `tools/list` would leave every unlisted operation callable by name. - **Read-only by default:** A non-`GET`/`HEAD` operation is refused unless `mutating_tools_enabled` is explicitly true. +- **Path arguments stay in their segment:** A value that fills a `{placeholder}` of the contracted path is percent-encoded, and an empty value or one made only of dots is refused, so a call cannot resolve to a path the contract does not name. - **Enforced ceilings:** Request size, response size, timeout, concurrency, page size and result count come from the contract and are applied, not merely declared. - **Bounded ranges:** A tool whose schema declares `start`, `end` and `step` has its point count checked against `result_items` and is refused with the smallest step that fits, so the upstream never scans a range whose result the adapter would discard. - **Fail-closed on drift:** A tool contract whose hash no longer matches its pinned `schema_sha256` refuses to start. diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py index fc4ed18be2..b527da2b6c 100644 --- a/roles/svc-ai-mcp-adapter/files/python/policy.py +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -47,6 +47,7 @@ DENY_TOO_MANY_REQUESTS = "too_many_concurrent_requests" DENY_UNKNOWN_ARGUMENT = "undeclared_argument" DENY_MISSING_ARGUMENT = "missing_required_argument" DENY_RANGE_TOO_WIDE = "range_too_wide" +DENY_PATH_ARGUMENT = "path_argument_not_a_segment" RANGE_ARGUMENTS = ("start", "end", "step") @@ -189,6 +190,17 @@ def assert_arguments( raise PermissionError(f"{DENY_MISSING_ARGUMENT}: {name!r} requires {missing}") +def assert_path_arguments( + spec: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> None: + path = str(spec["path"]) + for key, value in (arguments or {}).items(): + if "{" + key + "}" in path and not str(value).strip("."): + raise PermissionError( + f"{DENY_PATH_ARGUMENT}: {name!r} takes no {str(value)!r} as {key!r}" + ) + + def parse_instant(value: Any) -> float: """Return a range boundary in unix seconds. @@ -217,10 +229,14 @@ def parse_duration(value: Any) -> float: return float(text) except ValueError: pass - parts = re.findall(r"(\d+)(ms|[smhdwy])", text) - if not parts or "".join(n + u for n, u in parts) != text: + *tokens, rest = re.split(r"(ms|[smhdwy])", text) + numbers, units = tokens[::2], tokens[1::2] + if rest or not numbers or not all(number.isdecimal() for number in numbers): raise ValueError(f"not a duration: {text!r}") - return sum(int(n) * DURATION_UNITS[u] for n, u in parts) + return sum( + int(number) * DURATION_UNITS[unit] + for number, unit in zip(numbers, units, strict=True) + ) def assert_range( @@ -341,6 +357,7 @@ def authorize_call( ) assert_arguments(spec, name, arguments) + assert_path_arguments(spec, name, arguments) assert_range(spec, name, arguments, contract["limits"]["result_items"]) return method, str(spec["path"]) 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/test-e2e-cli/files/shared/mcp/contract.py b/roles/test-e2e-cli/files/shared/mcp/contract.py index 4af0b34781..f7997a1f7a 100644 --- a/roles/test-e2e-cli/files/shared/mcp/contract.py +++ b/roles/test-e2e-cli/files/shared/mcp/contract.py @@ -45,6 +45,7 @@ Environment: from __future__ import annotations +import contextlib import json import os import queue @@ -76,7 +77,7 @@ SESSION_TIMEOUT = 20 WRONG_CREDENTIAL = "Bearer " + "0" * 40 SESSION_HEADER = "Mcp-Session-Id" -SESSION = {"id": ""} +SESSION = {"id": "", "protocol": ""} def unguarded_url(): @@ -120,6 +121,8 @@ def rpc(method, params=None, authorization=None, url=None, notification=False): request.add_header("Authorization", authorization) if SESSION["id"]: request.add_header(SESSION_HEADER, SESSION["id"]) + if SESSION["protocol"]: + request.add_header("MCP-Protocol-Version", SESSION["protocol"]) try: with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin session = response.headers.get(SESSION_HEADER) @@ -320,21 +323,20 @@ class SseSession: self.content_type = self._response.headers.get("Content-Type", "") event = None try: - for raw in self._response: - line = raw.decode(errors="replace").rstrip("\r\n") - if line.startswith("event:"): - event = line.split(":", 1)[1].strip() - elif line.startswith("data:"): - data = line.split(":", 1)[1].strip() - if event == "endpoint": - self.endpoint = urllib.parse.urljoin(self.url, data) - self._announced.set() - else: - self._messages.put(data) - elif not line: - event = None - except (OSError, ValueError): - pass + with contextlib.suppress(OSError, ValueError): + for raw in self._response: + line = raw.decode(errors="replace").rstrip("\r\n") + if line.startswith("event:"): + event = line.split(":", 1)[1].strip() + elif line.startswith("data:"): + data = line.split(":", 1)[1].strip() + if event == "endpoint": + self.endpoint = urllib.parse.urljoin(self.url, data) + self._announced.set() + else: + self._messages.put(data) + elif not line: + event = None finally: self._announced.set() @@ -463,6 +465,8 @@ def main(): if status != 200: reject(f"authenticated initialize answered {status}: {body[:200]}") reject_error("authenticated initialize", rpc_error(body)) + result = json.loads(body).get("result") or {} + SESSION["protocol"] = result.get("protocolVersion", "") rpc("notifications/initialized", authorization=AUTH, notification=True) diff --git a/roles/web-app-confluence/README.md b/roles/web-app-confluence/README.md index aad1ee6b6a..abe03a2487 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-flowise/meta/services.yml b/roles/web-app-flowise/meta/services.yml index 4ec9bd5b04..a443b34f34 100644 --- a/roles/web-app-flowise/meta/services.yml +++ b/roles/web-app-flowise/meta/services.yml @@ -69,7 +69,7 @@ flowise: - key: sqlite_version type: npm package: better-sqlite3 - sqlite_version: 12.11.1 + sqlite_version: 13.0.3 custom: true name: flowise # nocheck: min-storage-headroom Reason: the deployed image is built here from node:24-slim and measures 4.8 GB, so the base image transfer is not its footprint diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index b145b4cc43..d64b434d28 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: @@ -111,11 +111,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 0ca62dc81d..87bb1ea8ec 100644 --- a/roles/web-app-gitea/vars/main.yml +++ b/roles/web-app-gitea/vars/main.yml @@ -78,7 +78,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 9ec60a41e8..0117ca615b 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 11b26f55fb..96dee4b054 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 2cdd59b9da..21c7f1b25a 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/README.md b/roles/web-app-moodle/README.md index 40cef02597..3f2e26f228 100644 --- a/roles/web-app-moodle/README.md +++ b/roles/web-app-moodle/README.md @@ -121,7 +121,7 @@ docker run --rm -it \ ## MCP server -The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `webservice/mcp` and served by the NGINX sidecar. +The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `public/webservice/mcp` and served by the NGINX sidecar. | Property | Value | | --- | --- | @@ -173,7 +173,13 @@ This is an accepted trade-off, not an oversight. Moodle offers no allowlist, so ## Image source -This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base. +This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base and installs the Composer dependencies that source declares. The NGINX sidecar serves the `public` directory of the code volume and hands every other path to Moodle's router. + +## Updates + +The image carries the Moodle release pinned as `services.moodle.app_version` in `meta/services.yml`. On start the entrypoint compares that release with the one recorded in the code volume. When the image is newer, it copies the image's tree next to the old one and swaps them once the copy is complete. An image that is older than the recorded release refuses to start. `tasks/01_manager_ops.yml` then runs `admin/cli/upgrade.php`, which migrates the database. + +Plugins installed through the web interface live only in the code volume and are not carried over to the next release. Declare a plugin under `meta/addons/` so the image ships it. ## Further Resources diff --git a/roles/web-app-moodle/files/Dockerfile b/roles/web-app-moodle/files/Dockerfile index dc36c5be3a..f6aa1f92c2 100644 --- a/roles/web-app-moodle/files/Dockerfile +++ b/roles/web-app-moodle/files/Dockerfile @@ -96,6 +96,8 @@ COPY build/php-conf/opcache-recommended.ini /usr/local/etc/php/conf.d/opcache-re COPY build/php-conf/moodle-runtime.ini /usr/local/etc/php/conf.d/moodle-runtime.ini COPY build/php-conf/zz-moodle-pool.conf /usr/local/etc/php-fpm.d/zz-moodle-pool.conf +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer + COPY build/install/moodle-source.sh /tmp/install-moodle-source.sh RUN bash /tmp/install-moodle-source.sh && rm /tmp/install-moodle-source.sh diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 5434affc26..5e66fb1fcd 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -40,6 +40,7 @@ $CFG->dataroot = moodle_env('MOODLE_DATAROOT'); $CFG->localcachedir = moodle_env('MOODLE_LOCALCACHEDIR'); $CFG->admin = 'admin'; $CFG->directorypermissions = 02770; +$CFG->routerconfigured = true; $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); diff --git a/roles/web-app-moodle/files/build/install/moodle-source.sh b/roles/web-app-moodle/files/build/install/moodle-source.sh index 8674cbc69f..17e5fa8df1 100644 --- a/roles/web-app-moodle/files/build/install/moodle-source.sh +++ b/roles/web-app-moodle/files/build/install/moodle-source.sh @@ -26,6 +26,8 @@ tar -xzf "${TARBALL_PATH}" --strip-components=1 -C "${MOODLE_SOURCE_DIR}" test -d "${MOODLE_SOURCE_DIR}/${MOODLE_AUTH_SUBDIR}" test -f "${MOODLE_SOURCE_DIR}/${MOODLE_VERSION_FILE}" +COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --classmap-authoritative --no-interaction --working-dir="${MOODLE_SOURCE_DIR}" + mkdir -p "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" \ "${MOODLE_SOURCE_DIR}" "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" diff --git a/roles/web-app-moodle/files/build/moodle-entrypoint.sh b/roles/web-app-moodle/files/build/moodle-entrypoint.sh index 8474a21407..30083ff2ff 100644 --- a/roles/web-app-moodle/files/build/moodle-entrypoint.sh +++ b/roles/web-app-moodle/files/build/moodle-entrypoint.sh @@ -1,6 +1,6 @@ #!/bin/bash # Moodle container entrypoint. Bootstrap the persistent code volume -# from ${MOODLE_SOURCE_DIR} on first start, ensure ownership on the +# from ${MOODLE_SOURCE_DIR}, ensure ownership on the # data dir, then drop privileges (unless launching php-fpm โ€” its # master process must keep root so the FPM error log can write to # /proc/self/fd/2; workers fork to ${MOODLE_RUNTIME_USER} per the pool). @@ -14,9 +14,11 @@ set -euo pipefail : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_RUNTIME_USER:?required}" : "${MOODLE_VERSION_FILE:?required}" +: "${MOODLE_RELEASE:?required}" MOODLE_BOOTSTRAP_SENTINEL="${MOODLE_CODE_DIR}/.bootstrap.done" MOODLE_BOOTSTRAP_LOCK="${MOODLE_CODE_DIR}/.bootstrap.lock" +MOODLE_BOOTSTRAP_STAGE="${MOODLE_CODE_DIR}/.bootstrap.stage" mkdir -p "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_DATA_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error @@ -26,17 +28,36 @@ if [ "$(id -u)" -eq 0 ]; then chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_LOCAL_CACHE_DIR}" fi +moodle_code_dir_is_current() { + [ "$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" = "${MOODLE_RELEASE}" ] +} + +moodle_code_dir_is_newer() { + local recorded newest + recorded="$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" || return 1 + [ -n "${recorded}" ] || return 1 + newest="$(printf '%s\n' "${recorded}" "${MOODLE_RELEASE}" | sort -V | tail -n 1)" + [ "${newest}" = "${recorded}" ] && [ "${recorded}" != "${MOODLE_RELEASE}" ] +} + moodle_bootstrap_code_dir() { - if [ -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; then + if moodle_code_dir_is_current; then return 0 fi - if [ -d "${MOODLE_SOURCE_DIR}" ]; then - cp -an "${MOODLE_SOURCE_DIR}/." "${MOODLE_CODE_DIR}/" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + if moodle_code_dir_is_newer; then + echo "The code volume holds Moodle $(cat "${MOODLE_BOOTSTRAP_SENTINEL}"), this image ships the older ${MOODLE_RELEASE}; refusing to replace it." >&2 + exit 1 fi + rm -rf "${MOODLE_BOOTSTRAP_STAGE}" + mkdir "${MOODLE_BOOTSTRAP_STAGE}" + cp -a "${MOODLE_SOURCE_DIR}/." "${MOODLE_BOOTSTRAP_STAGE}/" + find "${MOODLE_CODE_DIR}" -mindepth 1 -maxdepth 1 ! -name "${MOODLE_BOOTSTRAP_LOCK##*/}" ! -name "${MOODLE_BOOTSTRAP_STAGE##*/}" -exec rm -rf {} + + find "${MOODLE_BOOTSTRAP_STAGE}" -mindepth 1 -maxdepth 1 -exec mv -t "${MOODLE_CODE_DIR}" {} + + rmdir "${MOODLE_BOOTSTRAP_STAGE}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_CODE_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type d -exec chmod 0755 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type f -exec chmod 0644 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - touch "${MOODLE_BOOTSTRAP_SENTINEL}" + printf '%s' "${MOODLE_RELEASE}" > "${MOODLE_BOOTSTRAP_SENTINEL}" } moodle_refresh_config() { @@ -51,7 +72,7 @@ moodle_refresh_config() { } mkdir -p "${MOODLE_CODE_DIR}" -while [ ! -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; do +until moodle_code_dir_is_current; do exec 9>>"${MOODLE_BOOTSTRAP_LOCK}" if flock -w 30 9; then moodle_bootstrap_code_dir 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/addons/auth_oidc.yml b/roles/web-app-moodle/meta/addons/auth_oidc.yml index 1e33ee4776..5d68112121 100644 --- a/roles/web-app-moodle/meta/addons/auth_oidc.yml +++ b/roles/web-app-moodle/meta/addons/auth_oidc.yml @@ -3,11 +3,11 @@ enabled: "{{ lookup('config', 'web-app-moodle', 'services.sso.enabled') | bool } required: false mechanism: plugin source: upstream -version: "v4.5.8" +version: "v5.2.1" bridges: - sso update: monitored: true catalog: github-releases upstream_id: microsoft/moodle-auth_oidc - match: "v4.5." + match: "v" diff --git a/roles/web-app-moodle/meta/server.yml b/roles/web-app-moodle/meta/server.yml new file mode 100644 index 0000000000..f365eb8102 --- /dev/null +++ b/roles/web-app-moodle/meta/server.yml @@ -0,0 +1,5 @@ +--- +status_codes: + default: + - 200 + - 303 diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 5e92907b72..ec3a325058 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -45,7 +45,7 @@ moodle: bond: 1 enabled: true # nocheck: dynamic-flag shared: true - app_version: 4.5.11 + app_version: 5.3.0 update: key: app_version type: git_tags @@ -64,7 +64,6 @@ moodle: pids_limit: 512 performance: php: - memory_limit: 512M upload_max_filesize: 256M post_max_size: 256M ports: diff --git a/roles/web-app-moodle/tasks/01_manager_ops.yml b/roles/web-app-moodle/tasks/01_manager_ops.yml index 078f32c1ca..93cd1d5e97 100644 --- a/roles/web-app-moodle/tasks/01_manager_ops.yml +++ b/roles/web-app-moodle/tasks/01_manager_ops.yml @@ -48,6 +48,13 @@ - "'Database tables already present' not in moodle_install.stderr" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "โฌ†๏ธ Upgrade the Moodle database to the release in the code volume" + shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ MOODLE_CLI_DIR }}/upgrade.php --non-interactive + register: moodle_upgrade + changed_when: "'No upgrade needed' not in moodle_upgrade.stderr" + - name: "๐Ÿ”‘ Realign the administrator password Moodle persisted at install" when: not (MOODLE_OIDC_ENABLED | bool) # nocheck: password-quote the token is upstream's CLI filename, not a credential diff --git a/roles/web-app-moodle/tasks/04_oidc.yml b/roles/web-app-moodle/tasks/04_oidc.yml index e150b4d5ed..2166ccec42 100644 --- a/roles/web-app-moodle/tasks/04_oidc.yml +++ b/roles/web-app-moodle/tasks/04_oidc.yml @@ -93,7 +93,7 @@ - { name: "field_map_lastnamephonetic", value: "name_phonetic_family" } - { name: "field_lock_lastnamephonetic", value: "locked" } - { name: "field_updatelocal_lastnamephonetic", value: "oneveryloginupdate" } - - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_RELPATH }}/" } + - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_URL_PATH }}/" } loop_control: label: "{{ item.name }}" shell: > 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/templates/nginx-moodle.conf.j2 b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 index 477b89cd1f..ca7b6a2a03 100644 --- a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 +++ b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 @@ -7,7 +7,7 @@ server { listen [::]:{{ MOODLE_NGINX_PORT }}; server_name _; - root {{ MOODLE_CODE_DIR }}; + root {{ MOODLE_PUBLIC_DIR }}; index index.php; client_max_body_size 256M; @@ -16,16 +16,19 @@ server { set $moodle_upstream {{ MOODLE_CONTAINER }}; location / { - try_files $uri $uri/ /index.php?$query_string; + try_files $uri $uri/ /r.php$is_args$args; } location ~ [^/]\.php(/|$) { - fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_split_path_info ^(.+\.php)(/.*)?$; + set $path_info $fastcgi_path_info; + try_files $fastcgi_script_name $fastcgi_script_name/ /r.php$is_args$args; fastcgi_index index.php; fastcgi_pass $moodle_upstream:{{ MOODLE_FPM_PORT }}; include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; + fastcgi_param DOCUMENT_ROOT $realpath_root; + fastcgi_param PATH_INFO $path_info; fastcgi_param HTTP_PROXY ""; fastcgi_read_timeout 300; } diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 2958c6ae54..7baefdccaa 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -19,15 +19,18 @@ MOODLE_BUILD_FILES: opcache_ini: "php-conf/opcache-recommended.ini" runtime_ini: "php-conf/moodle-runtime.ini" fpm_pool: "php-conf/zz-moodle-pool.conf" -MOODLE_VERSION_FILE: "version.php" # bootstrap-detection sentinel -MOODLE_AUTH_SUBDIR: "auth" # top-level auth/ tree -MOODLE_WEBSERVICE_SUBDIR: "webservice" +MOODLE_PUBLIC_SUBDIR: "public" +MOODLE_PUBLIC_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_PUBLIC_SUBDIR] | path_join }}" +MOODLE_VERSION_FILE: "{{ [MOODLE_PUBLIC_SUBDIR, 'version.php'] | path_join }}" +MOODLE_AUTH_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'auth'] | path_join }}" +MOODLE_WEBSERVICE_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'webservice'] | path_join }}" MOODLE_CLI_RELPATH: "admin/cli" # admin CLI script dir MOODLE_OIDC_PLUGIN_VERSION: "{{ lookup('config', application_id, 'addons.auth_oidc.version') }}" MOODLE_OIDC_PLUGIN_UPSTREAM: "{{ lookup('config', application_id, 'addons.auth_oidc.update.upstream_id') }}" MOODLE_OIDC_PLUGIN_ARCHIVE_URL: "https://github.com/{{ MOODLE_OIDC_PLUGIN_UPSTREAM }}/archive/refs/tags/{{ MOODLE_OIDC_PLUGIN_VERSION }}.zip" -MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_AUTH_SUBDIR, 'oidc'] | path_join }}" +MOODLE_OIDC_PLUGIN_URL_PATH: "auth/oidc" +MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_PUBLIC_SUBDIR, MOODLE_OIDC_PLUGIN_URL_PATH] | path_join }}" MOODLE_OIDC_PLUGIN_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_OIDC_PLUGIN_RELPATH] | path_join }}" MOODLE_CLI_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_CLI_RELPATH] | path_join }}" MOODLE_CONFIG: "{{ [MOODLE_CODE_DIR, 'config.php'] | path_join }}" @@ -130,7 +133,7 @@ MOODLE_SITE_TITLE: "{{ lookup('design', application_id).label }}" 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-n8n/files/javascript/hooks.js b/roles/web-app-n8n/files/javascript/hooks.js index 9b70bddff5..80e3f06db6 100644 --- a/roles/web-app-n8n/files/javascript/hooks.js +++ b/roles/web-app-n8n/files/javascript/hooks.js @@ -48,10 +48,12 @@ module.exports = { this.logger?.info(`SSO middleware initializing with header: ${headerName}`); - const Layer = require('router/lib/layer'); + const { createRequire } = require('module'); const { dirname, resolve } = require('path'); const { randomBytes } = require('crypto'); - const { hash } = require('bcryptjs'); + const n8nRequire = createRequire(require.resolve('n8n')); + const Layer = createRequire(n8nRequire.resolve('express'))('router/lib/layer'); + const { hash } = n8nRequire('bcryptjs'); const { issueCookie } = require(resolve(dirname(require.resolve('n8n')), 'auth/jwt')); // Trust the proxy for correct X-Forwarded-* handling and rate limiting @@ -114,18 +116,17 @@ module.exports = { this.logger?.info(`SSO auto-login attempt for email: ${userEmail}`); - // 1) Try to fetch the user (n8n 1.95.3 stores 'role' as a plain string column) let user = await UserRepo.findOne({ where: { email: userEmail }, + relations: ['role'], }); - // 2) If not found โ€” create the user (with 'global:member' role) and a project if (!user) { const hashed = await hash(randomBytes(16).toString('hex'), 10); const userData = { email: userEmail, - role: 'global:member', // string-based role is valid for createUserWithProject + role: { slug: 'global:member' }, password: hashed, }; if (userFirstName) userData.firstName = userFirstName; @@ -136,7 +137,6 @@ module.exports = { this.logger?.info(`Created new user: ${userEmail} (${userFirstName} ${userLastName}) via SSO`); } else { - // 3) Update first/last name if they changed upstream let changed = false; if (userFirstName && user.firstName !== userFirstName) { user.firstName = userFirstName; @@ -154,7 +154,6 @@ module.exports = { } } - // 4) Ensure 'user.role' exists (plain string column, e.g. 'global:member') if (!user.role) { this.logger?.error(`User ${userEmail} has no valid role; cannot issue cookie.`); res.statusCode = 401; @@ -162,10 +161,8 @@ module.exports = { return; } - // 5) Issue n8n auth cookie issueCookie(res, user); - // 6) Attach context for downstream middleware/routes req.user = user; req.userId = user.id; diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index fbc2d64aa0..b6c4b98888 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -73,7 +73,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "1.100.1" + version: "2.42.3" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index f041a7b0a1..2cf475c286 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 4fe768eb54..0c30dadeec 100644 --- a/roles/web-app-shopware/meta/services.yml +++ b/roles/web-app-shopware/meta/services.yml @@ -98,7 +98,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 7dccfea7e4..a98d537192 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/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 60fd5c6322..a56aa4270f 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.5.0 +version: v0.7.0 update: monitored: true catalog: github-releases 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 3be716defd..982a48a8e7 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('design', application_id).label }}" 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/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py index f7269a5a3c..e97744353b 100644 --- a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py +++ b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py @@ -22,7 +22,7 @@ import tempfile import unittest from pathlib import Path -from jinja2 import Template +from jinja2 import Template, select_autoescape from utils.cache.files import read_text @@ -62,7 +62,10 @@ class TestSshWrapperRsyncE2E(unittest.TestCase): (self.version_dir / "data" / "file2.txt").write_text("second") self.wrapper = self.work / "wrapper.sh" - rendered = Template(read_text(str(WRAPPER_TEMPLATE))).render( + rendered = Template( + read_text(str(WRAPPER_TEMPLATE)), + autoescape=select_autoescape(default_for_string=False), + ).render( DIR_BACKUPS=str(self.backups), BACKUP_REPOSITORIES=[BACKUP_TYPE], ) diff --git a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py index 4ed72e9dd0..e69326de26 100644 --- a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py +++ b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py @@ -1,7 +1,7 @@ import unittest from ansible.module_utils.parsing.convert_bool import boolean as ansible_boolean -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from tests.integration.roles import PROJECT_ROOT from utils.cache.files import read_text @@ -37,7 +37,7 @@ def _render_dnsmasq(**overrides): variables.update(overrides) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - dnsmasq config, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template("roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2") return template.render(**variables) @@ -146,7 +146,7 @@ class TestStaticBindSurvivesBoot(unittest.TestCase): self.assertLess(names.index(DROPIN_BLOCK), names.index(START_TASK)) reload_expression = start["ansible.builtin.systemd"]["daemon_reload"] - env = Environment(autoescape=False) # noqa: S701 - renders a boolean, not markup + env = Environment(autoescape=select_autoescape(default_for_string=False)) env.filters["bool"] = ansible_boolean env.tests["changed"] = lambda result: bool(result.get("changed", False)) @@ -192,7 +192,7 @@ class TestHostResolver(unittest.TestCase): task = next(t for t in tasks if t.get("name") == RESOLV_TASK) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - resolv.conf, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template( f"roles/svc-net-tor/templates/{task['ansible.builtin.template']['src']}" diff --git a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py index 921e159c9e..be0ac4d734 100644 --- a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py +++ b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py @@ -100,7 +100,7 @@ class TestShellTemplatesAreValid(unittest.TestCase): environment = jinja2.Environment( undefined=_Placeholder, keep_trailing_newline=True, - autoescape=False, # noqa: S701 shell, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) environment.filters = _PassthroughFilters(environment.filters) environment.filters["quote"] = shlex.quote diff --git a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py index b18f584947..d45f12251f 100644 --- a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py +++ b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py @@ -37,7 +37,9 @@ def _declared_space() -> tuple[list[ipaddress.IPv4Network], list[str]]: data = load_yaml_any(str(NETWORKS_FILE), default_if_missing={}) or {} pool = data.get("NETWORK_ROLE_SUBNET_POOL") if isinstance(pool, str) and "{{" in pool: - pool = jinja2.Template(pool).render(**data) + pool = jinja2.Template( + pool, autoescape=jinja2.select_autoescape(default_for_string=False) + ).render(**data) roles = data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES") or [] if not isinstance(pool, str) or not isinstance(roles, list): raise TypeError( diff --git a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py index 4ad33f9029..f2778df020 100644 --- a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py +++ b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py @@ -45,7 +45,6 @@ GATE = PROJECT_ROOT / ( ) _HEADER_RE = re.compile(r"x[-_]forwarded[-_]access[-_]token", re.IGNORECASE) _EMITS_RE = re.compile(r"proxy_set_header|auth_request_set") -_SKIP_DIRS = {".git", "node_modules", "__pycache__"} _TEXT_SUFFIXES = { ".js", ".mjs", diff --git a/tests/lint/ansible/roles/web-app/integration/test_email.py b/tests/lint/ansible/roles/web-app/integration/test_email.py index c5d3e7e2c1..7197c8451b 100644 --- a/tests/lint/ansible/roles/web-app/integration/test_email.py +++ b/tests/lint/ansible/roles/web-app/integration/test_email.py @@ -168,12 +168,6 @@ class TestWebAppRolesIntegrateEmail(unittest.TestCase): missing.append("enabled: true") if not is_explicit_truth(svc.get("shared")): missing.append("shared: true") - if missing: - rel = ( - config.relative_to(root).as_posix() - if config.is_file() - else role_path.relative_to(root).as_posix() - ) if not _role_pins_the_mail_relay(role_path): errors.append( f"[{role_path.name}]: calls lookup('email', ...) but no " 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_dotenv_quote.py b/tests/unit/python/plugins/filter/test_dotenv_quote.py index 9d61bddbdd..f05d3e37da 100644 --- a/tests/unit/python/plugins/filter/test_dotenv_quote.py +++ b/tests/unit/python/plugins/filter/test_dotenv_quote.py @@ -68,7 +68,9 @@ class TestDotenvQuoteModeAware(unittest.TestCase): """ def setUp(self): - env = jinja2.Environment(autoescape=False) # noqa: S701 - test renders a .env value, not HTML + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) env.filters["dotenv_quote"] = FilterModule().filters()["dotenv_quote"] self.env = env 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_alert_rule_roles.py b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py index 09953d117e..92cf702dbb 100644 --- a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py +++ b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py @@ -17,7 +17,6 @@ import unittest.mock as mock from pathlib import Path import plugins.lookup.alert_rule_roles as module -from plugins.lookup.alert_rule_roles import LookupModule class _Templar: @@ -29,7 +28,7 @@ class _Templar: def _make_lookup(vars_=None): - lm = LookupModule() + lm = module.LookupModule() lm._templar = _Templar(vars_ or {}) lm._loader = mock.MagicMock() return lm diff --git a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py index 4cb4765aca..28a633ccec 100644 --- a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py +++ b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py @@ -40,7 +40,9 @@ def _render(**answers) -> str: def _lookup(_plugin, _app, key): return values[key] - env = jinja2.Environment(autoescape=False) # noqa: S701 - renders SQL, HTML escaping would corrupt the literals + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) return env.from_string(read_text(str(_TEMPLATE))).render( lookup=_lookup, application_id="web-app-x" ) diff --git a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py index cfbc4d0e3a..72afc969bf 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py +++ b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py @@ -10,8 +10,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -40,7 +39,7 @@ class TestMcpClientBearerLookup(unittest.TestCase): def _run(self, terms, credential, role_credentials=None, users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_mcp_credential.py b/tests/unit/python/plugins/lookup/test_mcp_credential.py index fc67f6fb62..4c1b83d4b3 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_credential.py +++ b/tests/unit/python/plugins/lookup/test_mcp_credential.py @@ -9,8 +9,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -39,7 +38,7 @@ class TestMcpCredentialLookup(unittest.TestCase): def _run(self, terms, owner="mcp-web-app-gitea", users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_redirect_uris.py b/tests/unit/python/plugins/lookup/test_redirect_uris.py index 9a4772ea9a..ec7d98dc24 100644 --- a/tests/unit/python/plugins/lookup/test_redirect_uris.py +++ b/tests/unit/python/plugins/lookup/test_redirect_uris.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock as mock from ansible.errors import AnsibleError 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() diff --git a/tests/unit/python/roles/agents/test_mcp_tool_filter.py b/tests/unit/python/roles/agents/test_mcp_tool_filter.py index d4d8fa0149..4a09f37952 100644 --- a/tests/unit/python/roles/agents/test_mcp_tool_filter.py +++ b/tests/unit/python/roles/agents/test_mcp_tool_filter.py @@ -20,7 +20,7 @@ import json import unittest import yaml -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -82,7 +82,9 @@ def _yaml(text: str): def _render(directory, name, **context) -> str: - env = Environment(loader=FileSystemLoader(str(directory)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(directory)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/agents/test_openclaw_model_provider.py b/tests/unit/python/roles/agents/test_openclaw_model_provider.py index d7939d8710..4ce39d8ee8 100644 --- a/tests/unit/python/roles/agents/test_openclaw_model_provider.py +++ b/tests/unit/python/roles/agents/test_openclaw_model_provider.py @@ -16,7 +16,7 @@ import importlib.util import json import unittest -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -51,7 +51,9 @@ def _render(**overrides) -> dict: Args: overrides: context values replacing the defaults. """ - env = Environment(loader=FileSystemLoader(str(OPENCLAW)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(OPENCLAW)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return json.loads( env.get_template("openclaw.json.j2").render(**{**CONTEXT, **overrides}) diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py index e1728d0e72..3f21f05fe5 100644 --- a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py +++ b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest import yaml -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -72,7 +72,10 @@ def render(*, ollama=(), lmstudio=(), keys=None): lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed. keys: env-name -> provider key for the remote backends. """ - env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) env.filters["bool"] = _ansible_bool rendered = env.from_string(read_text(str(TEMPLATE))).render( LITELLM_OLLAMA_BACKEND=str(bool(ollama)), diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py index 376ac03ab3..c04c092e7a 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -4,6 +4,7 @@ from __future__ import annotations import importlib.util import json +import time import unittest from . import PROJECT_ROOT @@ -234,6 +235,26 @@ class TestDeclaredArguments(unittest.TestCase): self.assertEqual("GET", method) +class TestPathArguments(unittest.TestCase): + def call(self, **arguments): + return policy.authorize_call(contract(), "checkmk_get_host_status", arguments) + + def test_a_value_made_only_of_dots_is_refused(self): + for dots in range(4): + with self.subTest(dots=dots): + with self.assertRaises(PermissionError) as caught: + self.call(host="." * dots) + self.assertIn(policy.DENY_PATH_ARGUMENT, str(caught.exception)) + + def test_dots_inside_a_segment_pass(self): + for value in ("web-01.example", "..web", "web.."): + with self.subTest(value=value): + self.call(host=value) + + def test_a_query_argument_may_be_made_only_of_dots(self): + self.call(host="web-01", columns="." * 2) + + RANGE_TOOLS = { "prometheus_query_range": { "method": "GET", @@ -326,6 +347,22 @@ class TestDurationGrammar(unittest.TestCase): with self.assertRaises(ValueError): policy.parse_duration("1h30") + def test_anything_but_number_unit_pairs_is_refused(self): + for text in ("", "h", "1hh", "1.5h", "-1h", "1 h", "1sm", "abc"): + with self.subTest(text=text), self.assertRaises(ValueError): + policy.parse_duration(text) + + def test_a_long_digit_run_is_refused_in_linear_time(self): + started = time.monotonic() + with self.assertRaises(ValueError): + policy.parse_duration("0" * 20_000 + "!") + self.assertLess( + time.monotonic() - started, + 1.0, + "parsing must not rescan the digit run from every start position; " + "a backtracking pattern needs several seconds for this input", + ) + class TestAudit(unittest.TestCase): def test_the_event_names_both_sides_and_the_outcome(self): diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py index 99152196b5..ecadb860ef 100644 --- a/tests/unit/python/roles/svc-net-firewall/test_fragments.py +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -129,7 +129,7 @@ def _render(path: str, mode: str = "swarm") -> str: environment = jinja2.Environment( keep_trailing_newline=True, trim_blocks=True, - autoescape=False, # noqa: S701 nftables, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) return environment.from_string(read_text(path)).render( DEPLOYMENT_MODE=mode, **COMMON diff --git a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py index 67634ed302..a64c68528e 100644 --- a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py +++ b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py @@ -14,7 +14,7 @@ import os import sys import types import unittest -from unittest import mock +import unittest.mock as mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py index 52a558a9a9..7b04c193dd 100644 --- a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py +++ b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py @@ -16,7 +16,7 @@ from __future__ import annotations import importlib.util import sys import unittest -from unittest import mock +import unittest.mock as mock import jinja2 @@ -46,7 +46,9 @@ class _Templar: def template(self, value): return ( - jinja2.Environment(autoescape=False) # noqa: S701 - renders CIDRs, not markup + jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) .from_string(str(value)) .render(**self.available_variables) ) diff --git a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py index 4deb747de1..98528445a8 100644 --- a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py +++ b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py @@ -16,8 +16,8 @@ from __future__ import annotations import importlib.util import sys import unittest +import unittest.mock as mock from typing import Any -from unittest import mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py index 3e7e435f11..43acfc794f 100644 --- a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py +++ b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py @@ -18,7 +18,7 @@ import re import unittest from typing import Any, ClassVar -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -46,7 +46,7 @@ def _env() -> Environment: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["on_off"] = lambda value: "on" if value else "off" diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py index 8c6880baec..ee2610af0a 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.applications import get_application_defaults from utils.cache.yaml import load_yaml @@ -44,7 +44,7 @@ def render(name: str, **context) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; Ansible renders it the same way and HTML-escaping `$binary_remote_addr` would break it + autoescape=select_autoescape(), ) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py index cc2eaea1c3..7d2a7611e6 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py @@ -22,7 +22,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_MCP @@ -80,7 +80,7 @@ def render(role: str, *, exposure: str, sso_gated: bool = False) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; HTML-escaping would corrupt the directives + autoescape=select_autoescape(), ) env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub( pattern, repl, value diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py index f4fdf6163f..70086add9d 100644 --- a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py @@ -659,5 +659,79 @@ class TestSseSessionProbe(unittest.TestCase): self.assertIn("absent from the probed URL", stderr.getvalue()) +NEGOTIATED = "2025-03-26" + + +class StrictProvider: + def __init__(self): + self.seen = [] + self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) + threading.Thread(target=self._server.serve_forever, daemon=True).start() + + @property + def url(self): + host, port = self._server.server_address[:2] + return f"http://{host}:{port}/mcp" + + def stop(self): + self._server.shutdown() + self._server.server_close() + + def _handler(self): + provider = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length) or b"{}") + method = payload.get("method") + version = self.headers.get("MCP-Protocol-Version") + status, answer = 200, {"jsonrpc": "2.0", "id": payload.get("id")} + if self.headers.get("Authorization") != "Bearer real": + status, answer["error"] = 401, {"code": -32001, "message": "no"} + elif method == "initialize": + answer["result"] = {"protocolVersion": NEGOTIATED} + elif version != NEGOTIATED: + status = 400 + answer["error"] = { + "code": -32600, + "message": "MCP-Protocol-Version header is required", + } + elif method == "tools/list": + answer["result"] = { + "tools": [{"name": "a_get"}, {"name": "a_list"}] + } + else: + answer["result"] = {"isError": False, "content": []} + if method != "initialize": + provider.seen.append((method, version)) + body = json.dumps(answer).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + return Handler + + +class TestProtocolVersionHeader(unittest.TestCase): + def test_every_request_after_initialize_names_the_negotiated_version(self): + provider = StrictProvider() + self.addCleanup(provider.stop) + load({"MCP_URL": provider.url}).main() + self.assertEqual( + provider.seen, + [ + ("notifications/initialized", NEGOTIATED), + ("tools/list", NEGOTIATED), + ("tools/call", NEGOTIATED), + ], + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py index 4fb7076704..d924d3c71b 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment +from jinja2 import Environment, select_autoescape from utils.cache.yaml import load_yaml_any @@ -21,9 +21,9 @@ def until_expression() -> str: def settles(result: dict) -> bool: - template = Environment(autoescape=False).from_string( # noqa: S701 - ansible condition, not markup - "{{ " + until_expression() + " }}" - ) + template = Environment( + autoescape=select_autoescape(default_for_string=False) + ).from_string("{{ " + until_expression() + " }}") return template.render(_wait_result=result) == "True" diff --git a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py index 4198036cc3..ac76ffb055 100644 --- a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py +++ b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py @@ -17,7 +17,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -50,7 +50,7 @@ def _render(email: dict, ca_file: str = "") -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a Ruby config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["ruby_dq"] = lambda value: '"' + str(value).replace('"', '\\"') + '"' diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py index 008a48bd8f..249189de47 100644 --- a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py @@ -5,7 +5,7 @@ import json import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from . import PROJECT_ROOT @@ -102,7 +102,7 @@ def render(saml_apps: list[str], client_apps: list[str] | None = None) -> str: trim_blocks=True, keep_trailing_newline=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders JSON, where HTML escaping corrupts the value + autoescape=select_autoescape(), ) env.filters["path_join"] = path_join env.filters["to_json"] = json.dumps diff --git a/tests/unit/python/roles/web-app-moodle/__init__.py b/tests/unit/python/roles/web-app-moodle/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/__init__.py b/tests/unit/python/roles/web-app-moodle/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/__init__.py b/tests/unit/python/roles/web-app-moodle/files/build/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py new file mode 100644 index 0000000000..9ed0c5bcb0 --- /dev/null +++ b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py @@ -0,0 +1,124 @@ +import os +import pwd +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +ENTRYPOINT = PROJECT_ROOT / "roles/web-app-moodle/files/build/moodle-entrypoint.sh" + +FPM_STUB = "#!/usr/bin/env bash\nexit 0\n" + +LAYOUT_4 = {"version.php": "4.5.11", "auth/oidc/version.php": "4.5.8"} +LAYOUT_5 = {"public/version.php": "5.3.0", "public/auth/oidc/version.php": "5.2.1"} + + +class TestMoodleEntrypoint(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.source = self.root / "source" + self.code = self.root / "code" + bin_dir = self.root / "bin" + bin_dir.mkdir() + stub = bin_dir / "php-fpm" + stub.write_text(FPM_STUB) + stub.chmod(0o755) + self.env = dict(os.environ) + self.env.update( + PATH=f"{bin_dir}{os.pathsep}{self.env['PATH']}", + MOODLE_CODE_DIR=str(self.code), + MOODLE_DATA_DIR=str(self.root / "data"), + MOODLE_LOCAL_CACHE_DIR=str(self.root / "localcache"), + MOODLE_SOURCE_DIR=str(self.source), + MOODLE_RUNTIME_USER=pwd.getpwuid(os.getuid()).pw_name, + MOODLE_VERSION_FILE="public/version.php", + ) + + def write(self, tree, files): + for name, content in files.items(): + path = tree / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + def ship(self, files): + shutil.rmtree(self.source, ignore_errors=True) + self.write(self.source, files) + + def run_entrypoint(self, release): + return subprocess.run( + ["bash", str(ENTRYPOINT), "php-fpm"], + env={**self.env, "MOODLE_RELEASE": release}, + capture_output=True, + text=True, + check=False, + ) + + def start(self, release): + done = self.run_entrypoint(release) + self.assertEqual(done.returncode, 0, done.stderr) + + def shipped_files_in_the_volume(self): + return { + name for name in {*LAYOUT_4, *LAYOUT_5} if (self.code / name).is_file() + } + + def test_the_first_start_fills_the_code_volume(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_restart_on_the_same_release_keeps_what_the_volume_holds(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + added = {"public/local/extra/version.php": "added after the bootstrap"} + self.write(self.code, added) + self.start("5.3.0") + self.assertTrue((self.code / "public/local/extra/version.php").is_file()) + + def test_another_release_replaces_the_tree_and_drops_what_it_no_longer_ships(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_volume_the_previous_entrypoint_marked_done_is_replaced(self): + self.write(self.code, LAYOUT_4) + (self.code / ".bootstrap.done").touch() + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_missing_source_tree_fails_and_leaves_the_volume_unmarked(self): + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertFalse((self.code / ".bootstrap.done").exists()) + + def test_a_failed_copy_keeps_the_tree_the_volume_held(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + shutil.rmtree(self.source) + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_4)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "4.5.11") + + def test_an_image_older_than_the_recorded_release_refuses_to_replace_it(self): + self.ship(LAYOUT_5) + self.start("5.10.0") + self.ship(LAYOUT_4) + done = self.run_entrypoint("5.9.2") + self.assertNotEqual(done.returncode, 0) + self.assertIn("5.10.0", done.stderr) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "5.10.0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py index 4beccfb7b3..582607a82d 100644 --- a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py +++ b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -44,7 +44,7 @@ def jinja_env(searchpath) -> Environment: env = Environment( loader=FileSystemLoader(str(searchpath)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders HCL and dotenv, not markup + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["dotenv_quote"] = lambda value: f'"{value}"' diff --git a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py index 65304f0539..97205be309 100644 --- a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py +++ b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py @@ -465,7 +465,7 @@ class TestResolveApiKey(unittest.TestCase): modules = {} backend.install(modules) with patch.dict("sys.modules", modules): - return module, asyncio.run(module.resolve_api_key()) + return asyncio.run(module.resolve_api_key()) def test_an_existing_administrator_key_is_reused_and_kept(self) -> None: backend = FakeBackend( @@ -473,7 +473,7 @@ class TestResolveApiKey(unittest.TestCase): keys={"admin1": "sk-operator"}, ) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertEqual("sk-operator", key) @@ -483,7 +483,7 @@ class TestResolveApiKey(unittest.TestCase): def test_a_missing_key_is_minted_and_marked_for_removal(self) -> None: backend = FakeBackend([FakeUser("admin1", "admin")]) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertTrue(key.startswith("sk-")) @@ -493,7 +493,7 @@ class TestResolveApiKey(unittest.TestCase): def test_an_instance_without_users_gets_one_administrator(self) -> None: backend = FakeBackend([]) - _module, (user_id, _key, minted) = self._resolve(backend) + user_id, _key, minted = self._resolve(backend) self.assertEqual(["admin"], [user.role for user in backend.created]) self.assertEqual(backend.created[0].id, user_id) @@ -512,9 +512,8 @@ class TestResolveApiKey(unittest.TestCase): admin_id, _key, minted = asyncio.run(module.resolve_api_key()) self.assertTrue(minted) try: - exploding_grant(_key) - except RuntimeError: - pass + with self.assertRaises(RuntimeError): + exploding_grant(_key) finally: asyncio.run(module.drop_api_key(admin_id)) diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py index 3c57b00f2e..1ef49c2119 100644 --- a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py +++ b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py @@ -5,8 +5,8 @@ import struct import sys import tempfile import unittest +import unittest.mock as mock from pathlib import Path -from unittest import mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py index cf6ad49854..296133e61b 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py +++ b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py @@ -12,7 +12,7 @@ from __future__ import annotations import json import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -34,7 +34,7 @@ def _render(template_path, **variables) -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - JMAP request bodies, never HTML + autoescape=select_autoescape(default_for_string=False), ) env.filters["to_json"] = json.dumps env.filters["int"] = int diff --git a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py index 164ce94b0c..8261829975 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py +++ b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py @@ -16,7 +16,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -41,7 +41,7 @@ def _render(base_url: str, *, sso_enabled: bool = True, socks_proxy: str = "") - trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a PHP config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool return env.from_string(read_text(TEMPLATE)).render( diff --git a/tests/unit/python/utils/roles/test_guide.py b/tests/unit/python/utils/roles/test_guide.py index 49c3bcf1de..387edc71fd 100644 --- a/tests/unit/python/utils/roles/test_guide.py +++ b/tests/unit/python/utils/roles/test_guide.py @@ -1,6 +1,6 @@ import unittest +import unittest.mock as mock from typing import ClassVar -from unittest import mock from utils.cache.applications import get_variants from utils.roles.guide import guide_deployable, guide_variant, smallest_variant diff --git a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py index 4f27992dcb..b0773bf61e 100644 --- a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py +++ b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py @@ -1,7 +1,7 @@ import contextlib import io import unittest -from unittest import mock +import unittest.mock as mock from utils.tests.swarm import matrix