diff --git a/.dockerignore b/.dockerignore index 789d495e50..575b094162 100644 --- a/.dockerignore +++ b/.dockerignore @@ -48,9 +48,7 @@ compose/package-cache/pip.conf compose/package-cache/npmrc compose/package-cache/apt/*.list -# The i18n lane pins load_only to the languages a run translates, so the image -# bakes exactly those argos models instead of installing every one at runtime. -inventories/development/i18n.rendered.yml +inventories/development/tools.rendered.yml # Host shell / editor / tooling state accidentally surfaced inside this working copy .ansible diff --git a/.gitignore b/.gitignore index 789d495e50..575b094162 100644 --- a/.gitignore +++ b/.gitignore @@ -48,9 +48,7 @@ compose/package-cache/pip.conf compose/package-cache/npmrc compose/package-cache/apt/*.list -# The i18n lane pins load_only to the languages a run translates, so the image -# bakes exactly those argos models instead of installing every one at runtime. -inventories/development/i18n.rendered.yml +inventories/development/tools.rendered.yml # Host shell / editor / tooling state accidentally surfaced inside this working copy .ansible diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py index 50e552ada8..261d0719e2 100644 --- a/cli/administration/deploy/development/env.py +++ b/cli/administration/deploy/development/env.py @@ -29,7 +29,14 @@ def compose_file_args() -> list[str]: out += ["-f", "compose/gpu.override.yml"] if (os.environ.get("INFINITO_PUBLISH_PORTS") or "").strip().lower() == "false": out += ["-f", "compose/noports.override.yml"] - out += ["-f", "compose/i18n.override.yml"] + if all( + (os.environ.get(key) or "").strip() + for key in ( + "INFINITO_TOOLS_LIBRETRANSLATE_PORT", + "INFINITO_TOOLS_MODELS_HOST_PATH", + ) + ): + out += ["-f", "compose/tools.override.yml"] return out diff --git a/compose/cache.shared.override.yml b/compose/cache.shared.override.yml index 9aa36370fd..d397b339af 100644 --- a/compose/cache.shared.override.yml +++ b/compose/cache.shared.override.yml @@ -11,7 +11,7 @@ services: networks: cache: - i18n: + tools: networks: cache: diff --git a/compose/gpu.override.yml b/compose/gpu.override.yml index 4de6ac8e6b..8f1916db84 100644 --- a/compose/gpu.override.yml +++ b/compose/gpu.override.yml @@ -14,7 +14,7 @@ services: count: ${INFINITO_GPU_COUNT:?Run 'make dotenv' to generate the .env single source of truth} capabilities: [gpu] - i18n: + tools: deploy: resources: reservations: diff --git a/compose/i18n.override.yml b/compose/tools.override.yml similarity index 57% rename from compose/i18n.override.yml rename to compose/tools.override.yml index 97a74216b7..fac3301cb7 100644 --- a/compose/i18n.override.yml +++ b/compose/tools.override.yml @@ -1,14 +1,14 @@ --- -# Second runner for the i18n toolchain, with its own inner docker daemon and -# docker state. Gated behind the `i18n` compose profile. +# Second runner for the toolchain, with its own inner docker daemon and +# docker state. Gated behind the `tools` compose profile. services: - i18n: - image: "${INFINITO_IMAGE:?Resolved by cli.administration.deploy.development; the i18n runner reuses the image the infinito service builds}" + tools: + image: "${INFINITO_IMAGE:?Resolved by cli.administration.deploy.development; the tools runner reuses the image the infinito service builds}" pull_policy: never - container_name: ${INFINITO_CONTAINER:?Run 'make dotenv' to generate the .env single source of truth}_i18n + container_name: ${INFINITO_CONTAINER:?Run 'make dotenv' to generate the .env single source of truth}_tools profiles: - - i18n + - tools command: - /sbin/init - systemd.log_target=console @@ -28,8 +28,13 @@ services: volumes: - /sys/fs/cgroup:/sys/fs/cgroup:rw - .:${INFINITO_SRC_DIR} - - i18n-docker:${INFINITO_DOCKER_MOUNT:?Run 'make dotenv' to generate the .env single source of truth} - - i18n-var-lib:${INFINITO_DIR_VAR_LIB:?Run 'make dotenv' to generate the .env single source of truth}/ + - tools-docker:${INFINITO_DOCKER_MOUNT:?Run 'make dotenv' to generate the .env single source of truth} + - tools-var-lib:${INFINITO_DIR_VAR_LIB:?Run 'make dotenv' to generate the .env single source of truth}/ + - type: bind + source: ${INFINITO_TOOLS_MODELS_HOST_PATH:?Run 'make dotenv' to generate the .env single source of truth} + target: ${INFINITO_TOOLS_MODELS_HOST_PATH} + bind: + create_host_path: true environment: INFINITO_DIR_VAR_LIB: ${INFINITO_DIR_VAR_LIB} INFINITO_DNS_IP: ${INFINITO_DNS_IP} @@ -41,11 +46,11 @@ services: file: compose.cache-consumer.yml service: cache-consumer ports: - - "${INFINITO_BIND_IP:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_I18N_LIBRETRANSLATE_PORT:?Run 'make dotenv' to generate the - .env single source of truth}:${INFINITO_I18N_LIBRETRANSLATE_PORT:?Run 'make dotenv' to generate the .env single source of truth}" + - "${INFINITO_BIND_IP:?Run 'make dotenv' to generate the .env single source of truth}:${INFINITO_TOOLS_LIBRETRANSLATE_PORT:?Run 'make dotenv' to generate the + .env single source of truth}:${INFINITO_TOOLS_LIBRETRANSLATE_PORT:?Run 'make dotenv' to generate the .env single source of truth}" networks: default: volumes: - i18n-docker: - i18n-var-lib: + tools-docker: + tools-var-lib: diff --git a/default.env b/default.env index 5960d31c3c..6036a5fadb 100644 --- a/default.env +++ b/default.env @@ -64,14 +64,14 @@ INFINITO_CACHE_NETWORK= # Name of the Nexus container; the bootstrap reaches it by this name. INFINITO_CACHE_PACKAGE_CONTAINER=infinito-package-cache -# Host directory holding the package-cache frontend CA materials. -INFINITO_CACHE_PACKAGE_FRONTEND_CA_DIR=/var/cache/infinito/core/cache/package/frontend/ca +# Host directory holding the package-cache frontend CA materials; derived from DIR_CACHE. +INFINITO_CACHE_PACKAGE_FRONTEND_CA_DIR= # CA certificate file produced under INFINITO_CACHE_PACKAGE_FRONTEND_CA_DIR. -INFINITO_CACHE_PACKAGE_FRONTEND_CA_FILE=/var/cache/infinito/core/cache/package/frontend/ca/ca.crt +INFINITO_CACHE_PACKAGE_FRONTEND_CA_FILE= -# Host directory holding the package-cache frontend TLS certificates. -INFINITO_CACHE_PACKAGE_FRONTEND_CERTS_DIR=/var/cache/infinito/core/cache/package/frontend/certs +# Host directory holding the package-cache frontend TLS certificates; derived from DIR_CACHE. +INFINITO_CACHE_PACKAGE_FRONTEND_CERTS_DIR= # Init image used by the package-cache frontend cert-gen wrapper to run cert-gen.sh. INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE=alpine:latest @@ -79,8 +79,8 @@ INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE=alpine:latest # Static IPv4 address the package-cache frontend takes on the docker bridge. INFINITO_CACHE_PACKAGE_FRONTEND_IP=172.30.0.4 -# Host directory backing the Nexus 3 package-cache blobstore. -INFINITO_CACHE_PACKAGE_HOST_PATH=/var/cache/infinito/core/cache/package/data +# Host directory backing the Nexus 3 package-cache blobstore; derived from DIR_CACHE. +INFINITO_CACHE_PACKAGE_HOST_PATH= # Static IPv4 address the Nexus package-cache takes on the docker bridge. INFINITO_CACHE_PACKAGE_IP=172.30.0.5 @@ -100,11 +100,11 @@ INFINITO_CACHE_PACKAGE_PIP_CONF=./compose/package-cache/pip.conf # Host port the Nexus 3 package cache binds to on BIND_IP. INFINITO_CACHE_PACKAGE_PORT=8081 -# Host directory holding the registry-cache CA materials. -INFINITO_CACHE_REGISTRY_CA_HOST_PATH=/var/cache/infinito/core/cache/registry/ca +# Host directory holding the registry-cache proxy CA; derived from DIR_CACHE. +INFINITO_CACHE_REGISTRY_CA_HOST_PATH= -# Host directory backing the docker registry-mirror cache (bind mount). -INFINITO_CACHE_REGISTRY_HOST_PATH=/var/cache/infinito/core/cache/registry/mirror +# Host directory backing the registry-cache image mirror; derived from DIR_CACHE. +INFINITO_CACHE_REGISTRY_HOST_PATH= # Static IPv4 of the registry-cache; resolved via extra_hosts since coredns can't resolve the container name. INFINITO_CACHE_REGISTRY_IP=172.30.0.6 diff --git a/group_vars/all/05_paths.yml b/group_vars/all/05_paths.yml index d0a2ab7734..1ff25572d2 100644 --- a/group_vars/all/05_paths.yml +++ b/group_vars/all/05_paths.yml @@ -17,6 +17,8 @@ BIN_CA_INJECT: "{{ [ DIR_BIN, 'ca-inject' ] | path_join }}" BIN_CA_PHP_INI: "{{ [ DIR_BIN, 'ca-trust-php.ini' ] | path_join }}" BIN_RESOLVE_CONTAINER_ID: "{{ [ DIR_BIN, 'resolve-container-id' ] | path_join }}" +DIR_CACHE: "/var/cache/infinito/core/cache" + DIR_VAR_LIB: "/var/lib/infinito" DIR_BACKUPS: "{{ [DIR_VAR_LIB, 'backup'] | path_join }}" BACKUP_REPOSITORIES: diff --git a/inventories/development/i18n.yml b/inventories/development/i18n.yml deleted file mode 100644 index d910634d63..0000000000 --- a/inventories/development/i18n.yml +++ /dev/null @@ -1,27 +0,0 @@ ---- -# Host vars the i18n runner deploys web-svc-libretranslate with. - -TLS_MODE: self_signed - -TIMEOUT_FACTOR: 4 - -RESOURCE_HOST_CPUS_OVERRIDE: "{{ ansible_facts['processor_nproc'] }}" - -SIZE_PERCENT_CLEANUP_DISC_SPACE: 98 - -users: - administrator: - authorized_keys: - - ssh-ed25519 AAAA_TEST_DUMMY_KEY github-ci-dummy@infinito - -applications: - web-svc-libretranslate: - server: - tls: - mode: self_signed - services: - libretranslate: - directions: from_source - cpus: "{{ lookup('resource', 'host_cpus') }}" - mem_limit: "{{ lookup('resource', 'mem_limit') }}" - pids_limit: 4096 diff --git a/inventories/development/tools.yml.j2 b/inventories/development/tools.yml.j2 new file mode 100644 index 0000000000..4ddf65366e --- /dev/null +++ b/inventories/development/tools.yml.j2 @@ -0,0 +1,40 @@ +--- +# Host vars the tools runner deploys its toolchain services with. +# Rendered by utils.inventory.tools with square-bracket delimiters, so the +# curly-brace expressions below stay untouched for the deploy to resolve. + +TLS_MODE: self_signed + +TIMEOUT_FACTOR: 4 + +DOCKER_BIND_HOST: 0.0.0.0 + +RESOURCE_HOST_CPUS_OVERRIDE: "{{ ansible_facts['processor_nproc'] }}" + +SIZE_PERCENT_CLEANUP_DISC_SPACE: 98 + +users: + administrator: + authorized_keys: + - ssh-ed25519 AAAA_TEST_DUMMY_KEY github-ci-dummy@infinito + +applications: + svc-ai-libretranslate-engine: + services: + libretranslate-engine: + models_dir: [[ models_dir ]]/libretranslate + directions: from_source + load_only: +[% for code in load_only %] + - [[ code ]] +[% endfor %] + cpus: "{{ lookup('resource', 'host_cpus') }}" + mem_limit: "{{ lookup('resource', 'mem_limit') }}" + pids_limit: 4096 + svc-ai-s1: + secrets: + credentials: + api_key: [[ s1_api_key ]] + services: + s1: + models_dir: [[ models_dir ]]/s1 diff --git a/tests/unit/python/cli/administration/deploy/development/test_compose.py b/tests/unit/python/cli/administration/deploy/development/test_compose.py index 73696fe688..6f56e7f082 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_compose.py +++ b/tests/unit/python/cli/administration/deploy/development/test_compose.py @@ -128,7 +128,7 @@ class TestComposeUpRetries(unittest.TestCase): "-f", "compose.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", "ps", "-q", "infinito", @@ -174,7 +174,7 @@ class TestComposeUpRetries(unittest.TestCase): "-f", "compose/cache.override.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", "ps", "-q", "infinito", diff --git a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py index 63c4bceb61..ff9e5ebf24 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py +++ b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py @@ -23,6 +23,8 @@ _LOCAL_PRIMARY = { "INFINITO_CACHE_STACK": "", "INFINITO_PUBLISH_PORTS": "", "INFINITO_GPU_COUNT": "0", + "INFINITO_TOOLS_LIBRETRANSLATE_PORT": "8097", + "INFINITO_TOOLS_MODELS_HOST_PATH": "/var/cache/infinito/core/cache/models", } _WORKTREE = { @@ -44,7 +46,7 @@ class TestComposeFileArgs(unittest.TestCase): "-f", "compose/cache.override.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", ], ) @@ -62,7 +64,7 @@ class TestComposeFileArgs(unittest.TestCase): "-f", "compose/cache.shared.override.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", ], ) @@ -76,7 +78,7 @@ class TestComposeFileArgs(unittest.TestCase): "-f", "compose/cache.override.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", ], ) @@ -92,7 +94,7 @@ class TestComposeFileArgs(unittest.TestCase): "-f", "compose/cache.override.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", ], ) @@ -106,7 +108,7 @@ class TestComposeFileArgs(unittest.TestCase): "-f", "compose/worktree.override.yml", "-f", - "compose/i18n.override.yml", + "compose/tools.override.yml", ], ) @@ -114,7 +116,7 @@ class TestComposeFileArgs(unittest.TestCase): def test_ci_loads_no_override_at_all(self) -> None: self.assertEqual( compose_file_args(), - ["-f", "compose.yml", "-f", "compose/i18n.override.yml"], + ["-f", "compose.yml", "-f", "compose/tools.override.yml"], ) @patch.dict( @@ -137,6 +139,25 @@ class TestComposeFileArgs(unittest.TestCase): def test_a_host_with_a_gpu_adds_the_reservation(self) -> None: self.assertIn("compose/gpu.override.yml", compose_file_args()) + @patch.dict( + os.environ, + {**_LOCAL_PRIMARY, "INFINITO_TOOLS_LIBRETRANSLATE_PORT": ""}, + clear=False, + ) + def test_a_stale_env_drops_the_tools_lane_instead_of_aborting(self) -> None: + """The lane's override carries `:?` guards, which fire even behind its + profile, so layering it in against an .env that predates those keys + would abort every compose command rather than only the lane.""" + self.assertNotIn("compose/tools.override.yml", compose_file_args()) + + @patch.dict( + os.environ, + {**_LOCAL_PRIMARY, "INFINITO_TOOLS_MODELS_HOST_PATH": ""}, + clear=False, + ) + def test_the_models_path_gates_the_tools_lane_too(self) -> None: + self.assertNotIn("compose/tools.override.yml", compose_file_args()) + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/utils/env/handlers/__init__.py b/utils/env/handlers/__init__.py index 021d3ba35b..8f958eb746 100644 --- a/utils/env/handlers/__init__.py +++ b/utils/env/handlers/__init__.py @@ -37,6 +37,7 @@ from .infinito.ca import cert_host as ca_cert_host from .infinito.cache import conf as cache_conf from .infinito.cache import hosts as cache_hosts from .infinito.cache import http_hosts as cache_http_hosts +from .infinito.cache import paths as cache_paths from .infinito.cache import stack as cache_stack from .infinito.cache import tls as cache_tls from .infinito.cache import upstreams as cache_upstreams @@ -45,7 +46,6 @@ from .infinito.dir import secrets as dir_secrets from .infinito.dir import var_lib as dir_var_lib from .infinito.fork import account as fork_account from .infinito.fork import repository_url as fork_repository_url -from .infinito.i18n import libretranslate as i18n_libretranslate from .infinito.i18n import tuning as i18n_tuning from .infinito.package_cache import admin_password as package_cache_admin_password from .infinito.package_cache import blobstore_max as package_cache_blobstore_max @@ -60,6 +60,8 @@ from .infinito.running_on import act as running_on_act from .infinito.running_on import github as running_on_github from .infinito.swarm_nfs import export_base as swarm_nfs_export_base from .infinito.swarm_nfs import state_path as swarm_nfs_state_path +from .infinito.tools import libretranslate as tools_libretranslate +from .infinito.tools import models as tools_models from .infinito.worker import cpu as worker_cpu from .infinito.worker import fetch as worker_fetch @@ -89,6 +91,7 @@ ORDERED_HANDLERS = [ cache_tls, cache_upstreams, cache_stack, + cache_paths, tor_socks_port, is_wsl2, ca_bundle_candidates, @@ -109,7 +112,8 @@ ORDERED_HANDLERS = [ registry_cache_max_size, git_identity, gpu_count, - i18n_libretranslate, + tools_libretranslate, + tools_models, i18n_tuning, package_cache_heap, package_cache_direct_mem, diff --git a/utils/env/handlers/infinito/cache/paths.py b/utils/env/handlers/infinito/cache/paths.py new file mode 100644 index 0000000000..acc5696a0f --- /dev/null +++ b/utils/env/handlers/infinito/cache/paths.py @@ -0,0 +1,64 @@ +"""Host directories the cache stack keeps its state in. + +Every one of them sits below the cache base the paths SPOT defines +(``group_vars/all/05_paths.yml`` ``DIR_CACHE``), so the base is written once +and each service names only the leg below it. ``make clean-cache`` removes +three of these entries, not the base. + +Keys set here: the Nexus blobstore, the frontend's CA directory and file, its +TLS certificates, and the registry mirror's data and CA. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from utils.paths import read_group_path + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +ENTRIES: tuple[tuple[str, tuple[str, ...], str], ...] = ( + ( + "INFINITO_CACHE_PACKAGE_FRONTEND_CA_DIR", + ("package", "frontend", "ca"), + "Host directory holding the package-cache frontend CA materials.", + ), + ( + "INFINITO_CACHE_PACKAGE_FRONTEND_CA_FILE", + ("package", "frontend", "ca", "ca.crt"), + "CA certificate file produced under INFINITO_CACHE_PACKAGE_FRONTEND_CA_DIR.", + ), + ( + "INFINITO_CACHE_PACKAGE_FRONTEND_CERTS_DIR", + ("package", "frontend", "certs"), + "Host directory holding the package-cache frontend TLS certificates.", + ), + ( + "INFINITO_CACHE_PACKAGE_HOST_PATH", + ("package", "data"), + "Host directory backing the Nexus 3 package-cache blobstore.", + ), + ( + "INFINITO_CACHE_REGISTRY_CA_HOST_PATH", + ("registry", "ca"), + "Host directory holding the registry-cache proxy CA.", + ), + ( + "INFINITO_CACHE_REGISTRY_HOST_PATH", + ("registry", "mirror"), + "Host directory backing the registry-cache image mirror.", + ), +) + + +def base() -> Path: + """Return the cache base every entry below it derives from.""" + return Path(read_group_path("DIR_CACHE")) + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + root = base() + for key, legs, comment in ENTRIES: + eb.setdefault(key, str(root.joinpath(*legs)), comment=comment) diff --git a/utils/env/handlers/infinito/i18n/__init__.py b/utils/env/handlers/infinito/i18n/__init__.py index dd42ba3a81..922d0f267d 100644 --- a/utils/env/handlers/infinito/i18n/__init__.py +++ b/utils/env/handlers/infinito/i18n/__init__.py @@ -1 +1 @@ -"""Gettext and LibreTranslate env handlers.""" +"""Gettext env handlers.""" diff --git a/utils/env/handlers/infinito/tools/__init__.py b/utils/env/handlers/infinito/tools/__init__.py new file mode 100644 index 0000000000..79a83b5985 --- /dev/null +++ b/utils/env/handlers/infinito/tools/__init__.py @@ -0,0 +1 @@ +"""Tools lane env handlers.""" diff --git a/utils/env/handlers/infinito/i18n/libretranslate.py b/utils/env/handlers/infinito/tools/libretranslate.py similarity index 62% rename from utils/env/handlers/infinito/i18n/libretranslate.py rename to utils/env/handlers/infinito/tools/libretranslate.py index bdf0206f09..6c10f522d2 100644 --- a/utils/env/handlers/infinito/i18n/libretranslate.py +++ b/utils/env/handlers/infinito/tools/libretranslate.py @@ -1,5 +1,5 @@ -"""INFINITO_I18N_LIBRETRANSLATE_PORT: loopback port the i18n runner forwards to -its LibreTranslate, read from roles/web-svc-libretranslate/meta/services.yml.""" +"""INFINITO_TOOLS_LIBRETRANSLATE_PORT: loopback port the tools runner forwards +to its LibreTranslate, read from roles/svc-ai-libretranslate-engine/meta/services.yml.""" from __future__ import annotations @@ -12,9 +12,9 @@ from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: from utils.env.builder import BuildContext, EnvBuilder -KEY = "INFINITO_I18N_LIBRETRANSLATE_PORT" -COMMENT = "Loopback port the i18n runner forwards to its LibreTranslate." -SERVICES = f"roles/web-svc-libretranslate/{ROLE_FILE_META_SERVICES}" +KEY = "INFINITO_TOOLS_LIBRETRANSLATE_PORT" +COMMENT = "Loopback port the tools runner forwards to its LibreTranslate." +SERVICES = f"roles/svc-ai-libretranslate-engine/{ROLE_FILE_META_SERVICES}" HTTP_PORT = re.compile(r"^\s+local:\n\s+http:\s*(\d+)\s*$", re.MULTILINE) diff --git a/utils/env/handlers/infinito/tools/models.py b/utils/env/handlers/infinito/tools/models.py new file mode 100644 index 0000000000..8b6fe05c59 --- /dev/null +++ b/utils/env/handlers/infinito/tools/models.py @@ -0,0 +1,34 @@ +"""INFINITO_TOOLS_MODELS_HOST_PATH: node-local directory the tools lane keeps +its downloaded models in. + +A model is content-addressed and re-downloadable, so it belongs beside the +package and registry caches rather than in a docker volume: a bind survives +the runner, its volumes and an image rebuild, and every node keeps its own +copy instead of dragging gigabytes across a shared filesystem. + +The lane's inner docker resolves a bind against the runner's filesystem, so +``compose/tools.override.yml`` mounts this path into the runner under the same +name and ``inventories/development/tools.yml.j2`` points the roles at it. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from utils.env.handlers.infinito.cache.paths import base + +if TYPE_CHECKING: + from utils.env.builder import BuildContext, EnvBuilder + +KEY = "INFINITO_TOOLS_MODELS_HOST_PATH" +COMMENT = "Node-local directory the tools lane keeps its downloaded models in." +SEGMENT = "models" + + +def default() -> str: + """Return the models directory below the cache base the SPOT defines.""" + return str(base() / SEGMENT) + + +def apply(eb: EnvBuilder, ctx: BuildContext) -> None: + eb.setdefault(KEY, default(), comment=COMMENT) diff --git a/utils/i18n/libretranslate.py b/utils/i18n/libretranslate.py index 063d4be818..bb50bd6d2e 100644 --- a/utils/i18n/libretranslate.py +++ b/utils/i18n/libretranslate.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING from utils.cache.yaml import load_yaml from utils.i18n.client import LibreTranslate, Outcome, merge +from utils.inventory.tools import LANE_SERVICE from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: @@ -19,7 +20,8 @@ if TYPE_CHECKING: __all__ = ["LibreTranslate", "Outcome", "merge", "server"] -ROLE = "web-svc-libretranslate" +ROLE = "svc-ai-libretranslate-engine" +SERVICE_KEY = "libretranslate-engine" SERVICES_FILE = Path("roles") / ROLE / ROLE_FILE_META_SERVICES POLL_SECONDS = 5 READY_TIMEOUT_SECONDS = 3600 @@ -27,12 +29,10 @@ DEPLOYED_TIMEOUT_SECONDS = 5 DEPLOY_TIMEOUT_SECONDS = 4 * 3600 RUNNER_TIMEOUT_SECONDS = 300 SERVICE_TIMEOUT_SECONDS = READY_TIMEOUT_SECONDS -INVENTORY_DIR = Path.home() / "inventories" / "infinito-i18n" +INVENTORY_DIR = Path.home() / "inventories" / "infinito-tools" DEPLOY_PID_FILE = Path("build") / "deploy.pid" DEPLOY_ROUTER = "deploy/main.sh" -GPU_STAMP = Path("build") / "i18n-gpu.stamp" -INVENTORY_VARS = Path("inventories") / "development" / "i18n.yml" -INVENTORY_VARS_RENDERED = Path("inventories") / "development" / "i18n.rendered.yml" +GPU_STAMP = Path("build") / "tools-gpu.stamp" PIVOT_LANGUAGE = "en" @@ -61,7 +61,7 @@ def service_url(root: Path) -> str: Args: root: repository root. """ - service = load_yaml(root / SERVICES_FILE)["libretranslate"] + service = load_yaml(root / SERVICES_FILE)[SERVICE_KEY] host = environment(root)["INFINITO_BIND_IP"] return f"http://{host}:{service['ports']['local']['http']}" @@ -164,7 +164,7 @@ def local_image(root: Path, env: dict[str, str]) -> str: def await_runner(name: str, env: dict[str, str]) -> None: - """Block until the i18n runner is up, so no exec falls back to another container. + """Block until the tools runner is up, so no exec falls back to another container. Args: name: container name of the runner. @@ -185,7 +185,7 @@ def await_runner(name: str, env: dict[str, str]) -> None: if state.stdout.strip() == "true": return time.sleep(POLL_SECONDS) - raise RuntimeError(f"The i18n runner {name} did not reach the running state.") + raise RuntimeError(f"The tools runner {name} did not reach the running state.") def baked_languages(root: Path) -> list[str]: @@ -208,34 +208,30 @@ def _vars_file(root: Path) -> Path: ``load_only`` reaches the Dockerfile as a build ARG, so a value that follows the batch rebuilds the prefetch layer on every run and refetches - every model in it. Pinning the whole set keeps the ARG constant, and - ``from_source`` drops the reverse pairs this lane never asks for. + every model in it. Pinning the whole set keeps the ARG constant. Args: root: repository root. Returns: - The rendered file, beside the tracked one so the container sees it. + The rendered file, beside the template so the container sees it. """ - from utils.cache.yaml import dump_yaml, load_yaml + from utils.inventory.tools import render - loaded = load_yaml(str(root / INVENTORY_VARS)) - service = loaded["applications"][ROLE]["services"]["libretranslate"] - service["load_only"] = baked_languages(root) - service["directions"] = "from_source" - rendered = root / INVENTORY_VARS_RENDERED - dump_yaml(rendered, loaded) - return rendered + return render(root, baked_languages(root)) -def deploy(root: Path) -> str: - """Deploy web-svc-libretranslate alone into its own inventory and return its URL. +def deploy(root: Path, roles: tuple[str, ...] = (ROLE,)) -> str: + """Deploy the named roles into the tools lane's own inventory. Args: root: repository root. + roles: the application ids to provision and deploy. Defaults to the + translation engine, so the i18n targets are unaffected by callers + that bring up a different tool. Returns: - The base URL, empty when the service stays unreachable. + The translation engine's base URL, empty when it stays unreachable. """ from cli.administration.deploy.development.env import compose_file_args @@ -248,7 +244,7 @@ def deploy(root: Path) -> str: "-T", "-w", loaded["INFINITO_SRC_DIR"], - "i18n", + LANE_SERVICE, "python", "-m", ] @@ -259,10 +255,10 @@ def deploy(root: Path) -> str: "compose", *compose_file_args(), "--profile", - "i18n", + LANE_SERVICE, "up", "-d", - "i18n", + LANE_SERVICE, ], [*inside[:-2], "sh", "-lc", "/usr/local/bin/package-frontend-ca.sh"], [*inside[:-2], "systemctl", "daemon-reload"], @@ -272,7 +268,7 @@ def deploy(root: Path) -> str: "cli.administration.inventory.provision", str(INVENTORY_DIR), "--include", - ROLE, + *roles, "--vars-file", f"{loaded['INFINITO_SRC_DIR']}/{_vars_file(root).relative_to(root)}", ], @@ -335,12 +331,12 @@ def server(root: Path) -> Iterator[str]: def lane_container(env: dict[str, str]) -> str: - """Return the name of the container the i18n lane deploys into. + """Return the name of the container the tools lane deploys into. Args: env: the process environment the deploy CLIs expect. """ - return f"{env['INFINITO_CONTAINER']}_i18n" + return f"{env['INFINITO_CONTAINER']}_{LANE_SERVICE}" def download_status(root: Path) -> str: diff --git a/utils/inventory/tools.py b/utils/inventory/tools.py new file mode 100644 index 0000000000..d7bb9a900d --- /dev/null +++ b/utils/inventory/tools.py @@ -0,0 +1,173 @@ +"""The tools lane: the host vars its services deploy with, and bringing it up. + +The lane holds the toolchain services the repository's own targets and tests +call: the translation engine behind the ``i18n`` targets, and the System One +classifier the semantic suite asks for a verdict. A caller names the roles it +needs and gets them running, so a check is never skipped merely because +nothing happened to be up. + +The template carries Ansible expressions the deploy resolves later, so it is +rendered with the Ansible parts inside ``raw`` blocks; everything this module +fills is an ordinary Jinja expression. The rendered file lands beside the +template so the runner's bind mount of the repository exposes it inside the +container. + +Nothing here deploys a cache: the runner extends ``compose.cache-consumer.yml`` +from the outer stack, so its image pulls already traverse ``registry-cache`` +and its package and model downloads resolve to ``package-cache-frontend`` +through that file's ``extra_hosts``. + +System One authenticates its callers, and its key is an +``algorithm: alphanumeric`` credential the provisioner would otherwise +generate into a vault the caller cannot read back. :data:`API_KEY` pins one +instead, so the lane and the checks that call it agree without reading a vault +or passing a secret on a command line. It is a fixed literal because the lane +serves the repository's own tooling on a developer machine and reaches no +deployment that holds data, the same standing as the dummy authorized key the +template already carries. Never reuse it anywhere a real caller could reach. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from jinja2 import Environment, FileSystemLoader, StrictUndefined + +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +TEMPLATE = Path("inventories") / "development" / "tools.yml.j2" +RENDERED = Path("inventories") / "development" / "tools.rendered.yml" +API_KEY = "toolsLaneTestKeyNotASecret0000000000" +LIBRETRANSLATE_ROLE = "svc-ai-libretranslate-engine" +S1_ROLE = "svc-ai-s1" +LANE_SERVICE = "tools" + + +def models_dir() -> str: + """Return the node-local directory the lane keeps its models in. + + Reads the same value ``compose/tools.override.yml`` mounts into the + runner, so a bind the inventory writes resolves to the host directory + rather than to something inside the runner that a rebuild discards. + """ + from utils.env.handlers.infinito.tools.models import KEY, default + + return (os.environ.get(KEY) or "").strip() or default() + + +def lane_url(root: Path, role: str, service_key: str) -> str: + """Return the URL a container of the compose stack reaches a lane service on. + + The lane runs its services in a docker daemon of its own, inside the + runner container. The inventory pins ``DOCKER_BIND_HOST=0.0.0.0`` so + their ports are open on the runner's own interface, which the group_vars + default would not do (see ``inventories/development/tools.yml.j2``). The + runner and the rest of the stack share the compose network, which makes + the runner's service name the address to use. The host instead reaches + only the ports the runner republishes through ``compose/tools.override.yml``. + + Args: + root: repository root. + role: application id owning the service. + service_key: key under ``meta/services.yml``. + + Returns: + ``http://:``. + """ + services = load_yaml(root / "roles" / role / ROLE_FILE_META_SERVICES) + port = services[service_key]["ports"]["local"]["http"] + return f"http://{LANE_SERVICE}:{port}" + + +def render(root: Path, load_only: list[str]) -> Path: + """Write the tools lane host vars and return the rendered file. + + Args: + root: repository root. + load_only: every language code the lane's image prefetches models for. + Pinning the whole set keeps the build ARG constant, so the prefetch + layer is not rebuilt once per batch. + + Returns: + The rendered file. + """ + template_path = root / TEMPLATE + env = Environment( + loader=FileSystemLoader(str(template_path.parent)), + undefined=StrictUndefined, + keep_trailing_newline=True, + trim_blocks=True, + lstrip_blocks=True, + variable_start_string="[[", + variable_end_string="]]", + block_start_string="[%", + block_end_string="%]", + autoescape=False, # noqa: S701 - YAML output, HTML escaping would corrupt it + ) + body = env.get_template(template_path.name).render( + load_only=sorted(load_only), + s1_api_key=API_KEY, + models_dir=models_dir(), + ) + rendered = root / RENDERED + rendered.write_text(body, encoding="utf-8") + return rendered + + +def ensure(root: Path, roles: tuple[str, ...]) -> None: + """Bring the named lane roles up. + + Must run on the host: the lane is deployed with ``docker compose``, whose + bind mounts name host paths, so the same call from inside a container of + the stack resolves them against the wrong filesystem. + + Args: + root: repository root. + roles: application ids to deploy. + + Raises: + RuntimeError: a deploy already holds the container stack this one + would touch. + """ + from utils.i18n.libretranslate import deploy, deploying + + if deploying(root): + raise RuntimeError( + "A deploy is running; it shares the container stack the tools lane " + "would touch. Wait for it to finish and re-run. The running deploy " + "is left untouched." + ) + deploy(root, roles=roles) + + +def main(argv: list[str] | None = None) -> int: + """Bring the lane up for ``make test-oracle``, reporting why when it cannot. + + Exits 0 even when the lane stays down, because the checks that need it say + so themselves; a deploy that is already running is a reason to leave the + stack alone, not to fail the target. + + Args: + argv: application ids, defaulting to every role the lane serves. + """ + import argparse + + from utils import PROJECT_ROOT + + default_roles = [LIBRETRANSLATE_ROLE, S1_ROLE] + parser = argparse.ArgumentParser(description="Bring the tools lane up.") + parser.add_argument("roles", nargs="*", default=default_roles) + args = parser.parse_args(argv) + roles = tuple(args.roles) or tuple(default_roles) + try: + ensure(Path(PROJECT_ROOT), roles) + except (RuntimeError, OSError, KeyError, subprocess.CalledProcessError) as down: + print(f"tools lane not brought up: {down!r}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())